PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label keyword. Show all posts
Showing posts with label keyword. Show all posts

Tuesday, December 13, 2022

[FIXED] When to use 'with' function and why is it good?

 December 13, 2022     keyword, r, syntax     No comments   

Issue

What are the benefits of using with()? In the help file it mentions it evaluates the expression in an environment it creates from the data. What are the benefits of this? Is it faster to create an environment and evaluate it in there as opposed to just evaluating it in the global environment? Or is there something else I'm missing?


Solution

with is a wrapper for functions with no data argument

There are many functions that work on data frames and take a data argument so that you don't need to retype the name of the data frame for every time you reference a column. lm, plot.formula, subset, transform are just a few examples.

with is a general purpose wrapper to let you use any function as if it had a data argument.

Using the mtcars data set, we could fit a model with or without using the data argument:

# this is obviously annoying
mod = lm(mtcars$mpg ~ mtcars$cyl + mtcars$disp + mtcars$wt)

# this is nicer
mod = lm(mpg ~ cyl + disp + wt, data = mtcars)

However, if (for some strange reason) we wanted to find the mean of cyl + disp + wt, there is a problem because mean doesn't have a data argument like lm does. This is the issue that with addresses:

# without with(), we would be stuck here:
z = mean(mtcars$cyl + mtcars$disp + mtcars$wt)

# using with(), we can clean this up:
z = with(mtcars, mean(cyl + disp + wt))

Wrapping foo() in with(data, foo(...)) lets us use any function foo as if it had a data argument - which is to say we can use unquoted column names, preventing repetitive data_name$column_name or data_name[, "column_name"].

When to use with

Use with whenever you like interactively (R console) and in R scripts to save typing and make your code clearer. The more frequently you would need to re-type your data frame name for a single command (and the longer your data frame name is!), the greater the benefit of using with.

Also note that with isn't limited to data frames. From ?with:

For the default with method this may be an environment, a list, a data frame, or an integer as in sys.call.

I don't often work with environments, but when I do I find with very handy.

When you need pieces of a result for one line only

As @Rich Scriven suggests in comments, with can be very useful when you need to use the results of something like rle. If you only need the results once, then his example with(rle(data), lengths[values > 1]) lets you use the rle(data) results anonymously.

When to avoid with

When there is a data argument

Many functions that have a data argument use it for more than just easier syntax when you call it. Most modeling functions (like lm), and many others too (ggplot!) do a lot with the provided data. If you use with instead of a data argument, you'll limit the features available to you. If there is a data argument, use the data argument, not with.

Adding to the environment

In my example above, the result was assigned to the global environment (bar = with(...)). To make an assignment inside the list/environment/data, you can use within. (In the case of data.frames, transform is also good.)

In packages

Don't use with in R packages. There is a warning in help(subset) that could apply just about as well to with:

Warning This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences.

If you build an R package using with, when you check it you will probably get warnings or notes about using variables without a visible binding. This will make the package unacceptable by CRAN.

Alternatives to with

Don't use attach

Many (mostly dated) R tutorials use attach to avoid re-typing data frame names by making columns accessible to the global environment. attach is widely considered to be bad practice and should be avoided. One of the main dangers of attach is that data columns can become out of sync if they are modified individually. with avoids this pitfall because it is invoked one expression at a time. There are many, many questions on Stack Overflow where new users are following an old tutorial and run in to problems because of attach. The easy solution is always don't use attach.

Using with all the time seems too repetitive

If you are doing many steps of data manipulation, you may find yourself beginning every line of code with with(my_data, .... You might think this repetition is almost as bad as not using with. Both the data.table and dplyr packages offer efficient data manipulation with non-repetitive syntax. I'd encourage you to learn to use one of them. Both have excellent documentation.



Answered By - Gregor Thomas
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 9, 2022

[FIXED] Why enum is a reserved keyword in vanilla javascript?

 July 09, 2022     javascript, keyword     No comments   

Issue

I was trying to declare a variable named enum but got Uncaught SyntaxError: Unexpected reserved word error.

I'm not using typescript, so why is enum a reserved keyword?

I was searching for it and realized that enum is a reserved keyword, but protected is also reserved and doesn't give me the error.

enter image description here

I also couldn't find what enum is used for or how it works in vanilla js.


Solution

According to the docs

The following are reserved as future keywords by the ECMAScript specification. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.

And enum is always reserved keyword.



Answered By - Vencovsky
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check if a keyword is present regardless of capitalization?

 July 09, 2022     java, javascript, keyword, node.js     No comments   

Issue

I am writing a program that looks for specific keywords and then only performs an action when a keyword is present in a message. I am having difficulty trying to make it so that it will pickup on keywords regardless of their capitalization. Below is an example of what I currently have.

for (var i = 0; i < keyword.length; i++) {

      if (msg.content.includes (keyword[i])) {
      msg.channel.send("Orange")
      }

var keyword = ["Apple","Banana"] 

The only way I've figured out how to do this is to add each variation to the keyword list. How would I make it so that it could detect for example "apple" or "BaNaNa" without adding those variations to the keyword list?


Solution

If your message is a string, just make the whole thing lower case and match it to lowercase keywords.

let message = msg.content.toLowerCase();
if (message.includes(keyword[i].toLowerCase()) {
    ....
}


Answered By - Ed Lucas
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to do Keyword matching across different dataframes in Pandas?

 July 09, 2022     dataframe, keyword, pandas, python, text-mining     No comments   

Issue

I have 2 dataframes across which I need to map the keywords. The input data(df1) looks like this:

    keyword            subtopic     
    post office        Brand        
    uspshelp uspshelp  Help         
    package delivery   Shipping     
    fed ex             Brand        
    ups fedex          Brand        
    delivery done      Shipping     
    united states      location     
    rt ups             retweet      

This is the other dataframe (df2) which is to be used for keyword matching:

Key     Media_type  cleaned_text
910040  facebook    will take post office
409535  twitter     need help with upshelp upshelp
218658  facebook    there no section post office alabama ups fedex
218658  facebook    there no section post office alabama ups fedex
518903  twitter     cant wait see exactly ups fedex truck package
2423281 twitter     fed ex messed seedless
763587  twitter     crazy package delivery rammed car
827572  twitter     formatting idead delivery done
2404106 facebook    supoused mexico united states america
1077739 twitter     rt ups

I want to map the 'keyword' column in df1 to the 'cleaned_text' column in df2 based on few conditions:

  1. One row in 'keyword' can be mapped to more than one row in 'cleaned_text' (One to many relationship)
  2. It should select the whole keyword together and not just individual words.
  3. If a 'keyword' matches to more than one row in 'cleaned_Text' it should create new records in the output dataframe(df3)

This is how the output dataframe(df3) should look like:

Key     Media_type  cleaned_text                                    keyword               subtopic  
910040  facebook    will take post office                           post office           Brand 
409535  twitter     need help with upshelp upshelp                  uspshelp uspshelp     Help  
218658  facebook    there no section post office alabama ups fedex  post office           Brand 
218658  facebook    there no section post office alabama ups fedex  ups fedex             Brand 
518903  twitter     cant wait see exactly ups fedex truck package   ups fedex             Brand 
2423281 twitter     fed ex messed seedless                          fed ex messed         Brand 
763587  twitter     crazy package delivery rammed car               package delivery      Shipping  
827572  twitter     formatting idead delivery done                  delivery done         Shipping  
2404106 facebook    supoused mexico united states america           united states america location  
1077739 twitter     rt ups                                          rt ups                retweet               

Solution

How about converting your df1 into a dictionary? And then loop through your df2 and search for matches. It is maybe not the most efficient way, but it is very readable

keyword_dict = {row.keyword: row.subtopic for row in df1.itertuples()}
df3_data = []
for row in df2.itertuples():
    text = row.cleaned_text
    for keyword in keyword_dict:
        if keyword in text:
            df3_row = [row.Key, row.Media_type, row.cleaned_text, keyword, keyword_dict[keyword]]
            df3_data.append(df3_row)

df3_columns = list(df2.columns) + list(df1.columns)
df3 = pd.DataFrame(df3_data, columns=df3_columns)


Answered By - chatax
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to split the input based by comparing two dataframes in pandas

 July 09, 2022     dataframe, keyword, pandas, python, split     No comments   

Issue

I am trying to take the input and keyword in the two tables from the database. So am using pandas to read both the tables and using the respective columns for splitting up of data and then write back the output in the same table in DB.

My input:

Original_Input

LARIDENT SRL
MIZUHO Corporation Gosen Factory
ZIMMER MANUFACTURING BV
GALT MEDICAL CORP
MIZUHO AMERICA INC
AVENT S de RL de CV
LUV N CARE LTD
STERIS ISOMEDIX PUERTO RICO INC
MEDISTIM INC
Cadence Science Inc
TECHNOLOGIES SA
AMG Mdicale Co Inc

My keyword table:

**Name_Extension**                 **Company_Type**        **Priority**
  co llc                             Company LLC                2
  Pvt ltd                            Private Limited            8
  Corp                               Corporation                4
  CO Ltd                             Company Limited            3
  inc                                Incorporated               5
  CO                                 Company                    1
  ltd                                Limited                    7
  llc                                LLC                        6
  Corporation                        Corporation                4
  & Co                               Company                    1
  Company Limited                    Company Limited            3
  Limited                            Limited                    7
  Co inc                             Company Incorporated       9
  AB                                  AB                        10
  SA                                  SA                        11
  S A                                 SA                        11
  GmbH                                GmbH                      12
  Sdn Bhd                             Sdn Bhd                   13
  llp                                 LLP                       14
  co llp                              LLP                       14
  SA DE CV                           SA DE CV                   19
  Company                            Company                    1 
  Coinc                              Company Incorporated       9
  Coltd                              Company Limited            3

So if the input(in table 1) has any of the name extension(this is in table 2) then it has to be split and put in as Core_input and Type_input columns where core input will contain the company names and type_input will contain the company type(from table 2 column 2) and it has to be checked with the priority.

My output will be:

Core_Input                                         Type_input
    NULL                                               NULL
    NULL                                               NULL
    NULL                                               NULL
   GALT MEDICAL                                    Corporation
   MIZUHO AMERICA                                   Incorporated
     NULL                                               NULL
   LUV N CARE                                         Limited
 STERIS ISOMEDIX PUERTO RICO                         Incorporated
    MEDISTIM                                         Incorporated
   Cadence Science                                   Incorporated

My Code:

k1=[]
k2=[]

df1=pd.read_sql('select * from [dbo].[company_Extension]',engine)

for inp1 in df1['Name_Extension']:
    k1.append(inp1.strip())

for inp2 in df1['Company_Type']:
    k2.append(inp2.strip())


p=1
p1=max(df1['Priority'])

for k1 in df1['Name_Extension']:
    for k2 in df1['Company_Type']:
      #for pr in df1['Priority']:
         for i in df['Cleansed_Input']:
            while p<=p1:
                if re.search(r'[^>]*?\s'+str(k1).strip(),str(i).strip(),re.I) and (p == (pr for pr in 
                                                                               df1['Priority'])):
                    splits = i.str.split(str(k1),re.I)

                    df['Core_Input'] = splits[0] #df['Cleansed_Input'].str.replace(str(k1),'',re.I) 

                    df['Type_input'] = str(k2)
                 p=p+1
data.to_sql('Testtable', con=engine, if_exists='replace',index= False)

Any help is appreciated.

Edit:

df=pd.read_sql('select * from [dbo].[TempCompanyName]',engine)

df1=pd.read_sql('select * from [dbo].[company_Extension]',engine)

ext_list = df1['Name_Extension']
type_list =df1['Company_Type']

for i, j in df.iterrows():
    comp_name = df['Original_Input'][i]
    for idx, ex in enumerate(ext_list):
        if re.search(rf'\b{ex}\b', comp_name,re.IGNORECASE):
            df['Core_Input'] = type_list[idx]
            df['Type_input'].iloc[i] = comp_type

print(df)
df.to_sql('TempCompanyName', con=engine, if_exists='replace',index= False)


Edit:
ext_list = df1['Name_Extension']
type_list =df1['Company_Type']

for i, j in enumerate(df['Cleansed_Input']):
    comp_name = df['Cleansed_Input'][i]

    for idx, ex in enumerate(ext_list):
        comp_name.replace('.,','')
        if re.search(rf'(\b{ex}\b)', comp_name, re.I):
            comp_type = type_list[idx]
            df['Type_input'].iloc[i]= comp_type
            # Delete the extension name from company name
            updated_comp_name = 
            re.sub(rf'(\b{str(ex).upper()}\b)','',str(comp_name).upper())
            # Above regex is leaving space post word removal adding space 
            from next word becomes 2 spaces
            updated_comp_name = str(updated_comp_name).replace('  ',' ')
            # Update the company name
            df['Core_Input'].iloc[i] = updated_comp_name

Solution

Hi Hope below lines help you to get the solution...i am not using SQL due to some reason, but taken your data in 2 different excels...you need to add a column Type in input table before run the code...

import pandas as pd
import numpy
import re

input_df = pd.read_excel('input.xlsx',sheet_name='Sheet1')
exts_df = pd.read_excel('exts.xlsx', sheet_name='Sheet1')

# Check if correct data is loaded
print(input_df.head())

ext_list = exts_df['Name_Extension']
type_list =exts_df['Company_Type']

for i, j in input_df.iterrows():
    comp_name = input_df['Company Names'][i]
    for idx, ex in enumerate(ext_list):
        if re.search(rf'\b{ex}\b', comp_name,re.IGNORECASE):
            comp_type = type_list[idx]
            input_df['Type'].iloc[i] = comp_type
            # Delete teh extension name from company name
            updated_comp_name = re.sub(rf'\b{str(ex).upper()}\b','',str(comp_name).upper())
            # Above regex is leaving space post word removal adding space from next word becomes 2 spaces
            updated_comp_name = str(updated_comp_name).replace('  ',' ')
            # Update the company name
            input_df['Company Names'].iloc[i] = updated_comp_name

print(input_df)
input_df.to_excel('output.xlsx', index=False)

output post removal extension from input Company Name Column mapping Company_Type ...

enter image description here ...



Answered By - Hietsh Kumar
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the equivalent of the C# 'var' keyword in Java?

 July 09, 2022     java, keyword, var     No comments   

Issue

One use of the var keyword in C# is implicit type declaration. What is the Java equivalent syntax for var?


Solution

There is none. Alas, you have to type out the full type name.

Edit: 7 years after being posted, type inference for local variables (with var) was added in Java 10.

Edit: 6 years after being posted, to collect some of the comments from below:

  • The reason C# has the var keyword is because it's possible to have Types that have no name in .NET. Eg:

    var myData = new { a = 1, b = "2" };
    

    In this case, it would be impossible to give a proper type to myData. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.

  • var is not the same as dynamic. variables are still 100% statically typed. This will not compile:

    var myString = "foo";
    myString = 3;
    
  • var is also useful when the type is obvious from context. For example:

    var currentUser = User.GetCurrent();
    

    I can say that in any code that I am responsible for, currentUser has a User or derived class in it. Obviously, if your implementation of User.GetCurrent return an int, then maybe this is a detriment to you.

  • This has nothing to do with var, but if you have weird inheritance hierarchies where you shadow methods with other methods (eg new public void DoAThing()), don't forget that non-virtual methods are affected by the Type they are cast as.

    I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:

    class Foo {
        public void Non() {}
        public virtual void Virt() {}
    }
    
    class Bar : Foo {
        public new void Non() {}
        public override void Virt() {}
    }
    
    class Baz {
        public static Foo GetFoo() {
            return new Bar();
        }
    }
    
    var foo = Baz.GetFoo();
    foo.Non();  // <- Foo.Non, not Bar.Non
    foo.Virt(); // <- Bar.Virt
    
    var bar = (Bar)foo;
    bar.Non();  // <- Bar.Non, not Foo.Non
    bar.Virt(); // <- Still Bar.Virt
    

    As indicated, virtual methods are not affected by this.

  • No, there is no non-clumsy way to initialize a var without an actual variable.

    var foo1 = "bar";        //good
    var foo2;                //bad, what type?
    var foo3 = null;         //bad, null doesn't have a type
    var foo4 = default(var); //what?
    var foo5 = (object)null; //legal, but go home, you're drunk
    

    In this case, just do it the old fashioned way:

    object foo6;
    


Answered By - Mike Caron
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to eliminate incomplete strings?

 July 09, 2022     array-formulas, arrays, google-sheets, google-sheets-formula, keyword     No comments   

Issue

I have a list of keywords, but the program I am using truncates the list at 160 characters, so I am unable to fully see the last keyword string.

I want to use Google Sheets to remove the incomplete parts of the keyword list. This would mean removing the last element altogether, as the picture illustrates.

enter image description here

I have tried using the trimming function but without much success. How can incomplete strings (any string that contains three dots at the end) be removed from the list?


Solution

try:

=ARRAYFORMULA(IFNA(REGEXEXTRACT(A2:A, "(.*), ")))

0



Answered By - player0
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you use the user keyword "list"?

 July 09, 2022     c, keyword     No comments   

Issue

For a practical work I am working on I have to use a "preset" structure for certain functions. One of them was as follows:

int initEmployees(Employee* list, int len)
{

//From here is my code

    int isError = -1;
    if ( len > 0)
    {
        len--;
        for (int i = 0 ; i < len ; i++)
        {

//This line is the problem, I know is not right but not sure how to fix it
            list[i].isEmpty = 1;

/*My other guesses where:
*(list + i).isEmpty = 1;
(*Employee + i).isEmpty = 1;
but im quiet sure they won't work either*/

        }
        isError=0;
    }
    return isError;
}

Tried googling it: "Is codeblocks user keyword releted to STL!" and going through a 1991 C book (Spanish edit) checking if it contined references to any library containing it but nothing.


Solution

First up, list in this context is a variable name, not a keyword.

And there's nothing wrong with that loop code, provided that the Employee structure actually has an isEmpty member that you can assign 1 to.

It simply runs through a provided array (called list), setting each element in turn to be empty.

However, your manipulation of len seems a bit off, I suspect it won't modify the last element in the list since you decrement it before running the loop.

I suspect a more canonical version (including that fix) would be something like:

int initEmployees(Employee* list, int len) {
    // Error if no elements in list.

    if (len < 1) return -1;

    // Mark each entry as empty.

    for (int i = 0 ; i < len ; i++) {
        list[i].isEmpty = 1;
    }

    // Everything is okay.

    return 0;
}

But I'd also question raising an error on a list size of zero. It seems to me that it's perfectly okay to modify all elements of an empty list - that just involves doing nothing.

And, if you use unsigned values for sizes of things (e.g., size_t), your "negative" problem goes away.



Answered By - paxdiablo
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the 'when keyword' used for in T-SQL?

 July 09, 2022     keyword, sql-server, tsql     No comments   

Issue

What is the when keyword used for in T-SQL?

when

NOTE: I tried searching this on the web (e.g. 'Googling')... however due to the ubiquitous nature of the word 'when', I wasn't able to find a good explanation.

Furthermore, a list of SQL keywords did not include 'when' so either the list was not exhaustive or it is unique to T-SQL (or perhaps it was added in some 'newer' version of T-SQL / SSMS). Link to this particular SQL keyword site: https://www.w3schools.com/sql/sql_ref_keywords.asp


Solution

It's used in conjunction with the CASE keyword, which is like a switch, or 'if' statement essentially... for example:

SELECT 
    CASE WHEN [Column] = 1 THEN 'Column is 1'
         WHEN [Column] = 2 THEN 'Column is 2'
         ELSE 'Column is not 1 or 2'
         END AS [Description]


Answered By - Milney
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the difference between the keyword is and = in prolog?

 July 09, 2022     keyword, operators, prolog     No comments   

Issue

I'd appreciate it if someone could elaborate on the difference between the is keyword and the = operator in prolog. I saw this discussion in == and =, but it excludes is. The documentation talks about an unclear to me "unbound left operand." Can anyone elaborate?

I have a following example of is:

age(Person,X) :-
birth_year(Person,Y1),
current_year(Y2),
X is Y2-Y1. 

Is the difference assignment vs comparison? Any help is appreciated!

Edit: What is the relationship between == and is? I am not asking the relationship of == and =, unless I have a misunderstanding of the aforementioned relationship.


Solution

As usual, a bit of poking around helps:

?- X = 2 + 1. % unify X with 2 + 1
X = 2+1.

?- X = 2 + 1, write_canonical(X). % how does Prolog see X?
+(2,1)
X = 2+1.

?- is(X, +(2,1)). % evaluate the term +(2,1) as an arithmetic expression
                  % and unify X with the result
X = 3.

The point about X being a free variable is that since the result of the arithmetic expression is unified with it, you might get surprises when the terms are not the same even though the arithmetic expression seem as if they should be:

?- 1+2 is 2+1. % Evaluate 2+1 and try to unify with +(1,2)
false.

?- 1 is (1.5*2)-2. % Evaluates to 1.0 (float), unify with 1 (integer)
false.

?- 1+2 =:= 2+1.
true.

?- 1 =:= (1.5*2)-2.
true.

And please keep in mind that both =/2 and is/2 are predicates. They can also be just atoms, so they can also be names of functors. Both happen to be declared as operators. I don't think either should be called a "keyword".



Answered By - user1812457
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does C have keywords starting with underscore

 July 09, 2022     c, keyword     No comments   

Issue

Most keywords in C (or in any language for that matter) starts with a letter. But there are some keywords that starts with an underscore? They keywords are: _Alignas, _Alignof, _Atomic, _Bool, _Complex, _Generic, _Imaginary, _Noreturn, _Static_assert and _Thread_local.

I find it amazingly strange. If it was a hidden global constant or internal function that's not really a part of the API, I would understand it. But these are keywords.

I find it extra strange when C actually have a macros called bool and static_assert, and that their implementations is using the very keywords I just mentioned.


Solution

C developed and become very popular before it was planned by a standards committee. In consequence, there was a lot of existing code.

When setting a C standard, or updating an old standard, an important goal is not to “break” old code. It is desirable that code that worked with previous compilers continue to work with new versions of the C language.

Introducing a new keyword (or any new definition or meaning of a word) can break old code, since, when compiling, the word will have its new keyword meaning and not the identifier meaning it had with the previous compilers. The code will have to be edited. In addition to the expense of paying people to edit the code, this has a risk of introducing bugs if any mistakes are made.

To deal with this, a rule was made that identifiers starting with underscore were reserved. Making this rule did not break much old software, since most people writing software choose to use identifiers beginning with letters, not underscore. This rule gives the C standard a new ability: By using underscore when adding new keywords or other new meanings for words, it is able to do so without breaking old code, as long as that old code obeyed the rule.

New versions of the C standard sometimes introduce new meanings for words that do not begin with an underscore, such as bool. However, these new meanings are generally not introduced in the core language. Rather, they are introduced only in new headers. In making a bool type, the C standard provided a new header, <stdbool.h>. Since old code could not be including <stdbool.h> since it did not exist when the code was written, defining bool in <stdbool.h> would not break old code. At the same time, it gives programmers writing new code the ability to use the new bool feature by including <stdbool.h>.



Answered By - Eric Postpischil
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I search for a certain line in a json file with a key word?

 July 09, 2022     json, keyword, python, search     No comments   

Issue

I want to know how to search for a line that has a certain name. This is my .txt file with json:

{"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}, {"name": "Larry", "website": "google.com", "from": "Michigan"}, {"name": "Tim", "website": "apple.com", "from": "Alabama"}]}

This is my code

import json

file = open('data.txt', "r")
read = file.read()
y = json.loads(read)

first = y["people"][0]
second = y["people"][1]
third = y["people"][2]

print(y["people"][0]["name"])

That prints out Scott, but is there a way to search the json file for the line with the name Scott? Ive tried print(y["people"]["name": "Scott"]) but that didnt work. I want the output to be {"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}


Solution

You can use a list comprehension to filter the list. e.g.

>>> people = y['people']
>>> people_named_scott = [p for p in people if p['name'] == 'Scott']
>>> people_named_scott
[{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]


Answered By - a'r
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the native keyword in Java for?

 July 09, 2022     java, java-native-interface, keyword, native     No comments   

Issue

While playing this puzzle (It's a Java keyword trivia game), I came across the native keyword.

What is the native keyword in Java used for?


Solution

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface).



Answered By - SLaks
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use reserved words without backquotes in MySQL

 July 09, 2022     cross-database, keyword, mysql, quotes, reserved     No comments   

Issue

I would like to use reserved words such as "user" or "right" as table or column names in my databases. Until now I've been using back quotes, but I read somewhere that they are MySQL specific, and I would like to preserve database compatibility. I've also read about using ANSI mode with MySQL to avoid using back quotes, but I want everything in my apps to be UTF-8.

What can I do to use reserved words without using back quotes or losing cross database compatibility ?


Solution

MySQL supports the ANSI standard of using double quotes surrounding identifiers such as table and column names. You have to enable this option since by default MySQL recognizes both single and double quotes as enclosing string literals:

http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_ansi_quotes



Answered By - bobwienholt
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to genrate keywords, hashtags or tags for a image with python?

 July 09, 2022     keyword, python     No comments   

Issue

I have seen it on Shutterstock or on many websites. if you upload an image with automatically generate suggested tags.


Solution

That's commonly done using (Deep) Artificial Neural Networks (NNs). The idea is that you feed an image into a trained NN model and it will predict a classification of the entire image, detect objects present in the image, or even label regions inside the image. There's a lot of freedom in what can be achieved. Since good models are not easy to obtain (without large amounts of data and intense training resources), there exist pretrained models that can be finetuned by the user in order to make it work on your own particular dataset (unfortunately, these models are often somewhat overfit to the dataset they have been trained on such that finetuning is necessary most of the time). I think this link will point you further into the direction how these automatically suggested tags can be generated.



Answered By - Daniel B.
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the equivalent in F# of the C# default keyword?

 July 09, 2022     c#, c#-to-f#, default, f#, keyword     No comments   

Issue

I'm looking for the equivalent of C# default keyword, e.g:

public T GetNext()
{
    T temp = default(T);
            ...

Thanks


Solution

I found this in a blog: "What does this C# code look like in F#? (part one: expressions and statements)"

C# has an operator called "default" that returns the zero-initialization value of a given type:

default(int) 

It has limited utility; most commonly you may use default(T) in a generic. F# has a similar construct as a library function:

Unchecked.defaultof<int>


Answered By - blu
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why are 'new' and 'make' not reserved keywords?

 July 09, 2022     go, identifier, keyword     No comments   

Issue

With syntax highlighting enabled, it's distracting while reading code like answer to this question with new used as a variable name.

I'm trying to think of a reason why only a subset of keywords would be reserved and can't come up with a good one.

Edit: Alternate title for this question:

Why are Go's predeclared identifiers not reserved ?


Solution

That's because new and make aren't really keywords, but built-in functions.

If you examine the full list of the reserved keywords, you won't see len or cap either...



Answered By - Elwinar
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the use of iter in python?

 July 09, 2022     iteration, keyword, python     No comments   

Issue

What is the use of using the iter function in python?

Instead of doing:

for i in range(8):
  print i

I could also use iter:

for iter in range(8):
  print iter

Solution

First of all: iter() normally is a function. Your code masks the function by using a local variable with the same name. You can do this with any built-in Python object.

In other words, you are not using the iter() function here. You are using a for loop variable that happens to use the same name. You could have called it dict and it would be no more about dictionaries than it is about Guido's choice of coffee. From the perspective of the for loop, there is no difference between your two examples.

You'd otherwise use the iter() function to produce an iterator type; an object that has a .next() method (.__next__() in Python 3).

The for loop does this for you, normally. When using an object that can produce an iterator, the for statement will use the C equivalent of calling iter() on it. You would only use iter() if you were doing other iterator-specific stuff with the object.



Answered By - Martijn Pieters
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the use of iter in python?

 July 09, 2022     iteration, keyword, python     No comments   

Issue

What is the use of using the iter function in python?

Instead of doing:

for i in range(8):
  print i

I could also use iter:

for iter in range(8):
  print iter

Solution

First of all: iter() normally is a function. Your code masks the function by using a local variable with the same name. You can do this with any built-in Python object.

In other words, you are not using the iter() function here. You are using a for loop variable that happens to use the same name. You could have called it dict and it would be no more about dictionaries than it is about Guido's choice of coffee. From the perspective of the for loop, there is no difference between your two examples.

You'd otherwise use the iter() function to produce an iterator type; an object that has a .next() method (.__next__() in Python 3).

The for loop does this for you, normally. When using an object that can produce an iterator, the for statement will use the C equivalent of calling iter() on it. You would only use iter() if you were doing other iterator-specific stuff with the object.



Answered By - Martijn Pieters
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to skip input according to keywords in ANTLR4

 July 09, 2022     antlr4, grammar, keyword, skip     No comments   

Issue

I am new to antlr4 and wonder if it can do what I am looking for. Here is an example input:

There is a lot of text 
in this file that i do not care 
about
Lithium 20 g/ml
Bor that should be skipped
Potassium  300g/ml
...

and code:

SempredParser.g4

parser grammar SempredParser;
options { tokenVocab=SempredLexer ;}

file        : line+ EOF;
line        : KEYWORD (NUM UNIT)+ '\n'+;

SempredLexer.g4:

lexer grammar SempredLexer;

//lexer rules

KEYWORD     : ('Lithium' | 'Potassium' ) ;
NL          : '\n';
NUM         : [0-9]+ ('.'[0-9]+)? ;
UNIT        : 'g/ml';
UNKNOWN     : . -> skip ;

I would like to skip all the lines that do not contain a KEYWORD (I have around 100 KEYWORDS). Note that I only use '\n' as delimiter here and would ideally not have it parsed to the output.

I read about Island grammars in the Definitive guide and also tried using lexer modes but could not make it work that way. Any hints and help greatly appreciated.


Solution

You are pretty close, just avoid to define a linebreak token twice. This grammar works for me (I put it into a combined grammar file):

grammar IslandTest;

start: NL+ line+ EOF;
line:  KEYWORD (NUM UNIT)+ NL+;

KEYWORD: ('Lithium' | 'Potassium');
NUM:     [0-9]+ ('.' [0-9]+)?;
UNIT:    'g/ml';

NL:      '\n';
UNKNOWN: . -> skip;

With your input that gives me this parse tree:

enter image description here

Note also: you cannot avoid the NL token in your output, because you decided to make your line parse rule line based, which requires the newline token.



Answered By - Mike Lischke
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing