text:
Q: Is there a way to limit cpu usage according to my clusters current resources? I want to limit a specific namespace to never leave less then a full cpu for my other namespaces (using a resources quota) and i have to problems in the way.:
a. Today i find the total amount of cpus using kubectl top nodes and divide the nominal cpu usage in the usage percentages, this is not accurate enough, is there a way to get my cluster total available cpu?
b. I would like to dynamically adjust to changes in the cluster (specifically added or removed nodes), a cronjob works fine but I'm looking for a way to hook major nodes changes, is there a known way to do that?

A: Not directly. You can set namespace level quotas easily enough but to make it that kind of dynamic thing you would need to make an operator or similar. A simple version would be a script running as a cron job which updates the Quota object.

A: Number of nodes CPUs is under .status.capacity.cpu in node object. You can print them e.g. with kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.capacity.cpu.
Dynamicaly adding/removing nodes can be achieved using autoscaler.


text:
Q: JavaScript get the first letter of the elements I want to make a program that get the first letter of all of the elements that have the same class.

var email = document.querySelector(".email");
var letter = document.querySelector(".letter");

const nameletter = email.textContent;
letter.innerHTML = nameletter.charAt(0);
.letter {
border: 1px solid red;
display: inline-block;
padding: 5px;
background-color: yellow;
}

email@email.com

anotheremail@email.com

As you can see, I can only get the first letter from the first element that has the 'email' class. Is there any way to get the second element's first letter?

A: You should be using querySelectorAll instead and iterating over them:

var email = document.querySelectorAll(".email");
var letter = document.querySelectorAll(".letter");

for(var i = 0; i < email.length; i++) {
  const nameletter = email[i].textContent;
  letter[i].innerHTML = nameletter.charAt(0);
}
.letter {
border: 1px solid red;
display: inline-block;
padding: 5px;
background-color: yellow;
}

email@email.com

anotheremail@email.com

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSRangeException error I am obj c n00b so forgive me if this is a dumb question, but my app is crashing when this JSON call is happening and it wasn't before. I am 95% positive it has something to do with the php call on the server. Would love any thoughts on this. :)
Thanks!
Here is where it breaks...
else if([ret_st hasPrefix:@"Account veri"]){

    NSMutableArray *Array=[ret_st componentsSeparatedByString:@"_"];
    appDelegate.user_id=[Array objectAtIndex:1];

NSLog(@"user_id %@",appDelegate.user_id);
2012-04-07 09:43:51.094 App[57919:15e03] request requestType=signup&name=Test&email=test@test.com&password=test&zip=90084&id=22   return_strr Account verified204
    2012-04-07 09:43:51.094 App[57919:15e03] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
    * First throw call stack:
    (0x1a23022 0x1e0ccd6 0x1a0f644 0xdb5d 0x10a85d 0x19f7936 0x19f73d7 0x195a790 0x1959d84 0x1959c9b 0x230d7d8 0x230d88a 0x442626 0x279d 0x2065)
    terminate called throwing an exception

A: Somewhere you have an array with one object in it at index 0 (bounds [0 .. 0]) but you are asking for an object at index 1 (index 1 beyond bounds).  Check your code for objectAtIndex: calls.


text:
Q: Converting Map to json I have a map called responseObj
Map<String, object> responseObj = new HashMap<String, Object>();

I have added some value in the responseObj like this -
responseObj.put("canApprove", true); //1
responseObj.put("approvers", userList);

The userList is a list or users -
List<User> userList = new ArrayList<User>();

The user Object from the User class -
class User {
 private int userId;
 private int roleId;
}

Now I have some questions -

*

*Is it possible to convert the responseObj to a json so that "canApprove" and "approvers" become key of json (see the code snippent below) and how can I make it?
{
 "canApprove" : true,
 "approver": [
{
  "userId": 309,
  "roleId": 2009
},
{
  "userId": 3008,
  "roleId": 2009
},

]
    }

*If I convert it into a json and get the response from jsp can I able get the appropriate boolean in jsp where the "canApprove" refers an Object in the responseObj?

*Can I persist the "userId" and "roleId" to JSON from User Class?

A: Try this :
public static class User
{
    public User(int userId, int roleId)
    {
        this.userId = userId;
        this.roleId = roleId;
    }
    private int userId;
    private int roleId;
    public int getUserId()
    {
        return userId;
    }
    public int getRoleId()
    {
        return roleId;
    }
    public void setUserId(int userId)
    {
        this.userId = userId;
    }
    public void setRoleId(int roleId)
    {
        this.roleId = roleId;
    }
}

Test :
Map<String, Object> responseObj = new HashMap<String, Object>();
List<User> userList = new ArrayList<User>();
userList.add(new User(1, 1));
userList.add(new User(2, 2));
responseObj.put("canApprove", true); //1
responseObj.put("approvers", userList);

System.out.println(new JSONObject(responseObj));

Prints :
{"approvers":[{"userId":1,"roleId":1},{"userId":2,"roleId":2}],"canApprove":true}

(formatted)

A: You can try to use JSONObject to parse the map to JSON.
The maven dependency is:
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>

later create a new JSON object and pass the map
JSONObject obj = new JSONObject(responseObj);

and return the object to this web client.

A: new com.google.gson.Gson().toJson(responseObj);

A: You can use some json serialization libraries to do this work for you, like fastjson or gson
1.Import the dependency jars into your project, add a <dependency> node into you pom.xml if you are using maven, or simply drop the jar in you project's library folder
2.String jsonString = JSON.toJSONString(responseObj); (using fastjson)


text:
Q: OpenLDAP: Retrieve parent DN What I have:
I have following hierarchy in my openldap setup.
Account '1-AA' has a user 'Foo'.
Base DN is
o=MyCompany,dc=sanjose,dc=corp,dc=company,dc=edu

Account is directly under Base DN.
What I want:
I want to display what is the account id (here 1-AA) for user 'Foo'.
What I know/tried:
Using standard java ldap search as
env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,"ldap://<host>:<port>/dc=sanjose,dc=corp,dc=company,dc=edu");
LdapContext ctx = new InitialLdapContext(env, null);
NamingEnumeration<?> namingEnum = ctx.search("o=MyCompany",
                "(user=Foo)", getSimpleSearchControls());
//hasNext loop
SearchResult result = (SearchResult) namingEnum.next();
System.out.println(result.getNameInNamespace());

Now the problem is that no result is returned in the above case. But if I try to get DN for Account 1-AA by changing search query to
NamingEnumeration<?> namingEnum = ctx.search("o=MyCompany",
                "(Account=1-AA)", getSimpleSearchControls());

it works fine.
How can I get the parent DN here. In English I just want to say give me all the Account Ids for while user=Foo.

A: Assuming searching for (user=Foo) does return the entry user=Foo,Account=1-AA,o=MyCompany,dc=sanjose,dc=corp,dc=company,dc=edu, then javax.naming.ldap.LdapName can get you the rest of the way. http://docs.oracle.com/javase/tutorial/jndi/newstuff/ldapname.html has an example of taking a prefix or suffix from a DN.


text:
Q: how write the result of vlookup pandas in a new csv file i try to write the result of a vlookup from an excel in a column of a second excel so i extract the series with this code, and it' work.
for exemple i've got in a first excel
a    b
1    10
5    17
1    19

i want to extract the column b when the column a = 1
so i use :
df5 = pd.read_excel(r'Y:\SIG-DROPBOX\3_Centre_de_Ressources\METADONNEES\SuiviGlobalMetadonnees.xlsm', None)
print ("df5")
print (df5.keys())
for feuille in df5:
    df1 = pd.read_excel(r'Y:\SIG-DROPBOX\3_Centre_de_Ressources\METADONNEES\SuiviGlobalMetadonnees.xlsm', feuille)
    # Notre fonction
    df3 = df1[df1["valide"]=="oui"]
    dada="Tables dans "+feuille+" (bases de données sde)"
    print (dada)
    df4 = df3[dada]
    print('df4')
    print (df4)

and so my script extract for the exemple:
b
10
19

now i want to put the result of my extract of an another excel with an existing column.
for exemple:
aa  bb  cc
    10
    19

but when i try to write the result of df4 with tis code:
df6 = pd.ExcelWriter(r'C:\data\remplissage.xls')
print('df6')
print (df6)
df4.to_excel(df6,'Nom_Mapservice')

nothing happens
can you help me to resolve my problem?

Hi everybody!
so i go forward with my script so i change the end to append the extract of my series (after df4)in a column of an  another xls.
so i write my script like this:

    listing = pd.Series(df4)
    print('listing')
    print (listing)

    df = pd.read_excel(r'C:\data\remplissage.xls',None)
    print (df)
    for feuille2 in df:
        print (feuille2)
        df6 = pd.read_excel(r'C:\data\remplissage.xls', feuille2)
        print (df6)
        df7 = df6['Tables dans DEV (bases de données sde)'].append(df4, ignore_index = True)
        print("df7")
        print (df7)

but nothing is happening
i don't hav an error and nothing append in the excel.
can you help me to solve that please

A: You should try this: df.to_excel('file_name.xlsx'), where df is the dataframe you want to write into excel and file_name is the name of the excel file you want to store in.


text:
Q: problem with defining a shortcut for \end{align} I define \beq=\begin{align} and \eeq=\end{align}.  \beq works correctly, but \eeq causes the error
! Paragraph ended before \align was complete.
<to be read again>
                   \par

any suggestions?


text:
Q: how to reduce multiple categorical predictors with large number of categories for classification? The dataset contains a few categorical variables with many categories(approx 10000 categories) in an ADs dataset.
The objective is to predict if ad will be clicked or not?
Could anyone suggest how to reduce these variable.
a few variables i have removed as they were nearzero variance predictors.


text:
Q: C sscanf: why is this segfaulting? I'm trying to take tokens in a format of "%i / %i%s" and split them into three variables.
char char1[20];
int int1;
int int2;

sscanf(token, "%[^/]/%d", char1, &int2);
printf("%s - %i ", char1, &int2);

It just segfaults.  What am I doing wrong?
I've tried changing %d to %i, with no difference.

A: You shouldn't print address of int2 in your printf. This is working for me:
const char *token = "qwerasdf/10";
char char1[20];
int int2;

sscanf(token, "%[^/]/%d", char1, &int2);
printf("%s - %i ", char1, int2);

Output:
qwerasdf - 10


text:
Q: Django: How to convert indexed QueryDict into array of QueryDicts? I am handling a POST request and I receive in request.data the following data structure:
<QueryDict: {'document[0]name': ['sample-0.pdf'], 'document[0]folder': ['folder-0'], 'document[1]name': ['sample-1.pdf'], 'document[1]category': ['file'], 'document[1]folder': ['folder-1']}>

How can I convert this to the following data structure:
[<QueryDict: {'name': ['sample-0.pdf'], 'folder': ['folder-0']}>, <QueryDict: {'name': ['sample-1.pdf'], 'category': ['file'], 'folder': ['folder-1']}>]


text:
Q: Track deleted user in SQL Server? Is it possible to track which user was deleted from SQL Server and when was it deleted?

A: If you're talking about detecting when new Server Logins are created and dropped, yes you can do that with server-wide DDL triggers. For example:
drop trigger if exists DDL_Server_Logins on all server;
go
create trigger DDL_Server_Logins
on all server
for create_login, drop_login
as
begin
    declare @event_type sysname, @command nvarchar(max)
    select @event_type = eventdata().value('(/EVENT_INSTANCE/EventType)[1]','nvarchar(128)'),
        @command = eventdata().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]', 'nvarchar(max)');
    print 'Server Cat is watching (' + @event_type + '): ' + @command;
end
go
create login doobey with password = N'Doobey Doobey Doo!';
go
drop login doobey;
go
drop trigger DDL_Server_Logins on all server;
go

Which outputs the following:
Server Cat is watching (CREATE_LOGIN): create login doobey with password = N'******';
Server Cat is watching (DROP_LOGIN): drop login doobey;

Notes:

*

*It's up to you to record where and when this happens, such as in audit tables.

*It's not retrospective - the trigger has to exist (and remain enabled) to capture these events in real time.

References:

*

*CREATE TRIGGER (Transact-SQL)

*Use the EVENTDATA Function

*DDL Events

A: If you have got audit setup already using any of the below means, you will be able to see when user was deleted.

*

*Profiler trace

*Server level triggers

*Extended events

*Monitoring tools

*any other auditing means

If you don't have any audit setup already, if you are having regular backups, you can find out, which users were deleted, between backups.


text:
Q: Logical And operator in the for loop I am Writing one script
It will access all the variables from one file and will use those variables in another script
In the var.sh file
MYSQL_LOGIN_USER="admin"
MYSQL_LOGIN_PASSWORD="admin@123"
declare -a MYSQL_USERS=("abc" "xyz") # declaring an array for mysql users
declare -a MYSQL_PASSWD=("abc@123" "xyz@123") #declaring an array for mysql passwords
MYSQL_DATABASE="database"

I Want to access both the array declared in var.sh file
In the main.sh file
source var.sh
echo "create database $MYSQL_DATABASE" | mysql -u $MYSQL_LOGIN_USER -p$MYSQL_LOGIN_PASSWORD
for i in "${MYSQL_USERS[@]}"
do
  echo "CREATE USER $i" | mysql -u $MYSQL_LOGIN_USER -p$MYSQL_LOGIN_PASSWORD
  echo "GRANT ALL PRIVILEGES ON $MYSQL_DATABASE.* TO $i IDENTIFIED BY $i" | mysql -u $MYSQL_LOGIN_USER -p$MYSQL_LOGIN_PASSWORD
done

In the above script I have used same name for user and password while granting privilages
I have tried using logical AND [&&] in the for loop but it is not working
Do i have to use nested for loops??

A: @AlastairCampbell is almost correct, but you need to index the arrays:
for i in "${!MYSQL_USERS[@]}"
do
    echo "CREATE USER ${MYSQL_USERS[$i]}" | mysql -u $MYSQL_LOGIN_USER -p$MYSQL_LOGIN_PASSWORD
    echo "GRANT ALL PRIVILEGES ON $MYSQL_DATABASE.* TO ${MYSQL_USERS[$i]}" IDENTIFIED BY ${MYSQL_PASSWD[$i]}" | mysql -u $MYSQL_LOGIN_USER -p$MYSQL_LOGIN_PASSWORD
done

Note that there are other issues with this script:

*

*You should use $(printf %q "$variable") to allow for special characters in any external variables.

*You can pass in SQL as a parameter rather than on standard input:
mysql -u $(printf %q "$MYSQL_LOGIN_USER") -p$(printf %q "$MYSQL_LOGIN_PASSWORD") "CREATE USER $(printf %q "${MYSQL_USERS[$i]}")"

*Nitpick, but you don't need to declare -a when assigning a literal - Bash figures that out automatically.

A: No, you can access the other array directly while in the loop if you get the count of the arguments rather than the arguments themselves.
Like so:
source var.sh
echo "create database $MYSQL_DATABASE" | mysql -u $MYSQL_LOGIN_USER -p$MYSQL_LOGIN_PASSWORD
for i in "${#MYSQL_USERS[@]}"
do
    echo "CREATE USER $MYSQL_USERS" | mysql -u $MYSQL_LOGIN_USER -p$MYSQL_LOGIN_PASSWORD
    echo "GRANT ALL PRIVILEGES ON $MYSQL_DATABASE.* TO $MYSQL_USERS IDENTIFIED BY $MYSQL_PASSWD" | mysql -u $MYSQL_LOGIN_USER -p$MYSQL_LOGIN_PASSWORD
done

Hope this helps. Please mark as correct answer if this answers your question.


text:
Q: Cursors in oracle PL/SQL I am trying to do a trigger that updates a status of a grade on update of the grade or a insert of a new one.
Thats my table
create table Enrollment (
   Student_ID char(9) not null,
   Course_ID char(5) not null,
   Registered_Date date,
   Grade NUMBER,
   Status varchar(4),
   constraint pkEnrollment primary key (Student_ID, Course_ID));

That's my code so far and i don't know what's the problem
create or replace TRIGGER PASS_FAIL
AFTER INSERT OR UPDATE OF GRADE ON ENROLLMENT
DECLARE
CURSOR change_grade IS
select GRADE, STATUS from ENROLLMENT FOR UPDATE;
 newgrade ENROLLMENT.GRADE%type;
 newstatus ENROLLMENT.STATUS%type;
BEGIN
  OPEN change_grade;
  LOOP
  FETCH change_grade into newgrade,newstatus;
  IF newgrade>=60 THEN UPDATE ENROLLMENT SET STATUS = 'Pass' WHERE CURRENT OF change_grade;
  ELSE UPDATE ENROLLMENT SET STATUS = 'Fail' WHERE CURRENT OF change_grade;
  END IF;
  EXIT WHEN change_grade%NOTFOUND;
  END LOOP;
  CLOSE change_grade;
END;

When i tried to change the grade i get
UPDATE "FELIX"."ENROLLMENT" SET GRADE = '10' WHERE ROWID = 'AAAGETAABAAALKJAAE' AND ORA_ROWSCN = '3332070'
ORA-04098: trigger 'FELIX.ELIGIBLE_ENROLLMENT' is invalid and failed re-validation

One error saving changes to table "FELIX"."ENROLLMENT":
Row 5: ORA-04098: trigger 'FELIX.ELIGIBLE_ENROLLMENT' is invalid and failed re-validation

Thanks in advance for the help

A: Your code seems excessively complicated unless the point is to learn about cursors.
CREATE OR REPLACE TRIGGER PASS_FAIL
   Before INSERT OR UPDATE
   ON enrollment
   REFERENCING NEW AS New OLD AS Old
   FOR EACH ROW
DECLARE
/******************************************************************************
   NAME:       PASS_FAIL
   PURPOSE:
   USED BY:
   REVISIONS:
   Ver        Date        Author           Description
   ---------  ----------  ---------------  ------------------------------------
   1.0              1. Created this trigger.

   NOTES:

******************************************************************************/

BEGIN
   if :new.grade > 60 THEN
     :new.status := 'PASS';
   ELSE
     :new.status := 'FAIL';
   END IF;
EXCEPTION
   WHEN OTHERS
   THEN
      -- Log the error and then re-raise
      RAISE;
END PASS_FAIL;


text:
Q: How use UTF-8 fonts with gem CombinePDF? I use gem combine_pdf for load existed pdf file and add some text (in French) to it.
But some specific charactets displaying poorly:
https://drive.google.com/file/d/1LAiK3JJTDjbVpgXrA9ITfCTeYSVws37x/view?usp=sharing
I try:
CombinePDF::Fonts.register_font(Rails.root.join('app/assets/fonts/slick.ttf'), font_metrics, Type: :Font)

font_metrics i take from Helvetica font from initiate_library function (CombinePDF::Fonts).
But it not work... What am I doing wrong?

A: I had the exact same problem with the combine_pdf gem. I did manage to fix it following the recommendations in the combine_pdf #137 issue.

*

*I created a PDF file with all the characters needed with a font that includes those characters (basically the entire alphabet, including the special characters é à ê as well as € or ' characters).

*Register the font as an available font in combine_pdf (e.g. your controller):
  fonts = CombinePDF.new(Rails.root.join('lib', 'data','font_template.pdf').to_s).fonts(true)
  CombinePDF.register_font_from_pdf_object :new_font, fonts[0]

*Set the font setting in your texbox to the new font with font: :new_font (or set it globally in an initialiser).

You can see a full example here in the combine_pdf_demo
The biggest problem for me was to correctly embed the new font in the PDF template. You need to make sure the fonts are actually embedded in the PDF, as sometimes system-fonts don't get properly embedded. Also make sure to include all the characters needed in your text.


text:
Q: Can I charge the battery with just a USB cable? While perusing a local second-hand charity shop, I stumbled upon a PSP for a steal!  However, the one "problem" mentioned by the clerk was that it was without a power supply.  After handling the device, I also noticed the battery had started to bulge.
I'm shopping around for an OEM battery at a reasonable price but while I wait I wanted to ask, can I charge the battery via the USB with just the USB cable?  Also, does it matter if the battery is completely dead?  I think I read somewhere that charging via USB is possible, however, you first have to cut on a couple settings from within a config menu.  If true, that seems unfortunate.
Anyway, I'd like to know the truth, for sure before buying a power adapter.  If getting one is inevitable, I may as well just order it with the battery.  Also, this is a PSP-3001 model, if that makes a difference.

A: Yes you can, although extremely slowly, just imagine it as the same thing as your phone.
Go to settings>system setting>USB charging-turn it on.
However, keep in mind there is a certain model that does not has that function:

PSP 1001 phat

The others, like yours, should.

A: PSP use lithium ion batteries. If it starts to bulge DO NOT RECHARGE IT. Bring it to a proper disposal place for such batteries.
Remember all the exploding laptops, phones and balancing-boards-that-some-people-think-hover? Yeah, lithium ion battery fire. You don't want that.
If there's a noticeable bulge don't use it, store it carefully and bring it to a proper disposal place (it's safe to handle as long as you don't do dumb things like heat or puncture it).


text:
Q: Python moving files and directories from one folder to another I would like to move in python files and directories in one directory to another directory with overwrite ability.
I started with the following code:
        #moving files from progs
        path = tempfolder + 'progs/'
        for dirs,files in os.listdir(path):
                 for f in files:
                        shutil.move(os.path.join(path, f) , os.path.join(compteurfolder, f))

So for the moment, I only try to move the files and I get the following errors:
    for dirs,files in os.listdir(path):
ValueError: too many values to unpack

I guess this is because I have dirs and files but then how will I move directories too? And how to make sure it can overwrite the files in the other folder?
Hope you can help.

A: The reason this fails:
for dirs,files in os.listdir(path):

… is that os.listdir just returns a list of filenames. So, each element is a string, and you're trying to unpack that string into two variables. Compare this:
a, b = (1, 2, 3, 4, 5, 6, 7, 8)
for a, b in [(1, 2, 3, 4, 5, 6, 7, 8), (9, 10)]
dirs, files = "spam.txt"
for dirs, files in ["spam.txt", "eggs.dat"]

It's the exact same error in every case—you can't fit 8 things into 2 variables.
Meanwhile, if listdir is just returning filenames, how do you know ones are the names of regular files, are which are the names of directories? You have to ask—e.g., by using isdir.
So:
for filename in os.listdir(path):
    if os.path.isdir(filename):
        # do directory stuff
    else:
        # do regular file stuff

(But note that this can still be confusing if you have symlinks…)

Meanwhile, what does "do regular file stuff" mean?
Well, assuming you don't have a directory (or a symlink to a directory) with the same name as the file you're trying to move there, as the docs for shutil.move say, os.rename or shutil.copy2 will be used. If you're not on Windows, this is perfect—if you have permission to overwrite the target you will, otherwise you'll get a permissions error. But if you are on Windows, os.rename will fail if the target already exists.
If you're on 3.3 or later, you can solve this by copying the shutil.move source* and using os.replace instead, as the rename docs imply. Otherwise, you will have to delete the target before renaming the source.
* Some stdlib modules—including shutil—are meant to serve as sample code as well as usable helpers. In those cases, at the top of the module's docs, there will be a Source code: link.

And what about "do directory stuff"? Well, if you move a directory spam to a target eggs/spam, and eggs/spam already exists as a directory, you're going to end up moving to eggs/spam/spam.
This shouldn't be surprising, as it's exactly the same thing mv on Unix and move on Windows do, which is what shutil is trying to simulate.
So, what you need to do here is delete the target (this time using shutil.rmtree) before moving the source.

Which means the simplest thing to do may be to not distinguish files and directories, Windows and Unix, or anything else; just do this:
for filename in os.listdir(path):
    target = os.path.join(compteurfolder, filename)
    try:
        shutil.rmtree(target)
    except NotADirectoryError:
        try:
            os.unlink(target)
        except FileNotFoundError:
            pass
    shutil.move(os.path.join(path, filename), target)

A: This because os.listdir(path) return array according documentation here. So you should modify you code as following for moving files and directories.
    #moving files from progs
    path = tempfolder + 'progs/'
    for item_path in os.listdir(path):
        shutil.move(os.path.join(path, item_path) , os.path.join(compteurfolder, item_path)

A: >>> import os
>>> import shutil

>>> for node in os.listdir(path):
...      if not os.path.isdir(node):
...          shutil.move(os.path.join(path, node) , os.path.join(compteurfolder, node))

A: (Python 3.6)
From a previous answer (can't add comment)
I think that the line
if not os.path.isdir(node):

Should read
if not os.path.isdir(os.path.join(source, node))

Otherwise it will always return True and move the sub folders as well.
>>> import os
>>> import shutil

>>> for node in os.listdir(path):
...      if not os.path.isdir(os.path.join(path, node)):
...          shutil.move(os.path.join(path, node) , os.path.join(compteurfolder, node))


text:
Q: Remove all phones from Google Directory User I am attempting to remove all phones from a Google Directory User, using the Admin Directory API directory_v1 > directory.users.update.
I am sending the following request body:
{
 "phones": []
}

but this seems to have no effect.
How can I achieve this?

A: Set it to null:
{
 "phones":null
}

See the note all the way at the bottom of the API documentation you linked to in the 'update' section.


text:
Q: Flex/Bison - match random data I'm implementing a custom CLI with flex/Bison. My sample command looks like this:
zone 3 set field some_value
where I can match keywords like zone and set, and I can match string in the place of field. However, at some_value can be anything, including keywords like 'zone'. The problem is that flex recognizes keywords like 'zone' in the position in some_value.
Moreover, I want spaces and any printing character in place of some_value.
This is my flex:
%option noyywrap nounput noinput
%option reentrant bison-bridge

digit [0-9]
integer [+-]?{digit}+
real [+-]?({digit}+[.]{digit}*)|({digit}*[.]{digit}+)
exp [+-]?({integer}|{real})[eE]-?{integer}
alpha [a-z][A-Z]+

%%

    /*subsystems*/
zone {
    return (cmd_sys_zone);
}
device {
    return (cmd_sys_device);
}
system {
    return (cmd_sys_system);
}
help {
    return (cmd_sys_help);
}
ver|version {
    return (cmd_sys_ver);
}

    /*actions*/
set {return (cmd_action_set);}
get {return (cmd_action_get);}
start {return (cmd_action_start);}
stop {return (cmd_action_stop);}

    /*Primitives*/
{integer} {
    yylval->number = strtoul(yytext, NULL, 0);
    return(cmd_num);
}

{real} {
    yylval->real = strtod(yytext, NULL);
    return(cmd_real);
}

{exp} {
    yylval->real = strtod(yytext, NULL);
    return(cmd_real);
}

[[:alpha:]]* {
    yylval->name = strdup(yytext);
    return(cmd_string);
}

[\n\r] {

}

[[:space:]]+  {

    //return(cmd_space);
} /* Do nothing */

. {
    yylval->name = strdup(yytext);
    showError();
//    return(cmd_other);
}

%%

void showError(){
    printf("Other input ");
}

int cmd_parse(cmd_t *command) {
    yyscan_t scanner;
    YY_BUFFER_STATE buffer;
    int ret_val;

    ret_val = 0;

    if ((ret_val = yylex_init(&scanner)) != 0) {
        goto exit_point;
    }

    buffer = yy_scan_buffer(command->buffer, command->len, scanner);
    yyparse(command, scanner);
    yy_delete_buffer(buffer, scanner);
    yylex_destroy(scanner);
exit_point:
    return 0;
}

This is my bision:
%{
#include <stdio.h>
#include <stdint.h>
#include "cmd.h"
#include "hmd.tab.h"

int yylex();
int yyerror(void *userdata, void *scanner, const char *s);

%}

%define api.pure

%define parse.error verbose

/*System tokens*/
%token cmd_sys_zone cmd_sys_device cmd_sys_system cmd_sys_ver cmd_sys_help

%token cmd_num cmd_string cmd_real

/*Action tokens*/
%token cmd_action_set cmd_action_get cmd_action_start cmd_action_stop

%type <number> cmd_num
%type <real> cmd_real
%type <name> cmd_string

%destructor {
    if ($$ == NULL) {
        free($$);
    }
} <name>

%union {
    char *name;
    uint64_t number;
    double real;
}

%parse-param {void *user_data}
%param {void *scanner}

%%

prog:
  stmts
;

stmts:
        | stmt stmts

stmt:
        cmd_sys_zone cmd_num cmd_action_set cmd_string cmd_string {
            cmd_zone_set(user_data, $2, $4, $5);
            cmd_free($4);
            cmd_free($5);
            } |
        cmd_sys_zone cmd_num cmd_action_get cmd_string {
            cmd_zone_get($2, $4);
            cmd_free($4);
            } |
        cmd_sys_ver {
            cmd_ver(user_data);
        } |
        cmd_sys_help {
            cmd_help();
            }

%%

int yyerror(void *userdata, void *scanner, const char *s)
{
    (void) scanner;
    (void) userdata;

    printf("Syntax Error on line %s\n", s);
    return 0;
}

I tried matching .*$, because my data always at the end of input, but that isn't working.

A: You have to use 'start states'. That is a feature of Flex.


text:
Q: How to translate a TypeORM query to a SQL statement? I have various queries in Typeorm and would like to convert them to SQL.
const id = parseInt(req.params.classId, 10);
const class = await getRepository(Class).findOne({ where: { id } });

Will this result in the following SQL query?
SELECT *
FROM class
WHERE id = classId

I'm struggling with the delete statement though.
isAdmin ? await getRepository(Class).delete({ id }) : await getRepository(Class).delete({ id, userId: req.user?.id ?? 0 });

How can I convert the above query to SQL?


text:
Q: font rendering issue in safari Hi currently i am working on one WordPress themes in which front page of theme look good on all browser but in safari when we go to any other page header of page which have heading ,tagline and on right side having small menu and contact detail goes wired means it's font goes more lighter than front page i need all consistent on all pages.
theme URL is here
please see in safari
Frontpage - http://demo.wpgothemes.com/minn
you can see any other page e.g -http://demo.wpgothemes.com/minn/page-layouts/3-col-content-center/
Thanks
Vishal

A: It solved by just adding
body
{
-webkit-font-smoothing: antialiased;
}


text:
Q: Select Event id from event table where event start date and event end date are same I have a Event table.
The attributes are:
 event_id,event_name,start_date,end_date.
I want to know all the id's where start_date and end_date are same.
How can I achieve this in mysql?

A: If you want to find all events that share the same start- and enddate you have to join the table with itself.
SELECT
  e1.event_id,
  e2.event_id
FROM
  event e1 JOIN event e2 ON (e1.event_id < e2.event_id AND
                             e1.start_date = e2.start_date AND
                             e1.end_date = e2.end_date)

Will join the event table with itself if the start_date and end_date of two distinct events are the same. The condition e1.event_id < e2.event_id is to prevent that the same event is joined with itself AND that a pair of matching events is reported twice (for example [event1,event22] and [event22,event1])


text:
Q: ASP.net MVC strongly typed view dropdownlist is empty For a Sitecore7 solution I setup an ASP.net MVC3 project. I'm trying to add a new view to my controller action using the "Add view" wizard, by clicking right on the View() code > Add view.
public class HomeController : SitecoreController
{
    public ActionResult Add()
    {
        return View();
    }
}

The "Add view" wizard shows up, but when I checked the checkbox "Create a strongly-typed view" the Model class dropdownlist is empty.
There are no build errors. However I cleaned, build and rebuild the solution, but that doesn't fix the problem. I'm using Visual Studio 2012 and the enviroment is completely updated.
I searched the internet and found this simular looking issue, but the solution doesn't fix the problem.
I have tried to fix it in a day, without success. Does anyone know a solution?
Thanks a lot.
Jordy

A: You can just type in the model at the top of your view, like this:
@model your.namespace.goes.here

A: 1.FIRST YOU DELETE ALL FILES IN YOUR APPLICATION BIN FOLDER.THEN TRY BUILD THE APPLICATION. OR
2.DO THE FIRST STEP AND IF YOU ARE USING EF TRY TO UPDATE YOUR DATABASE BY TYPING "update-database" from your package manager console

A: The simplest way to add a strongly-typed View is:
right click your Views folder -> Add -> Scaffold item -> MVC view
From there you can select whatever model and type you have available in the project. However, keep in mind that old MVC templates (like MVC 3) might not have all options available.


text:
Q: content-type; charset missing a space Using JAX-RS and Glassfish 3.1.2 I am trying to get the charset added to the content-type.
I've tried a few of the answers on SO, but I have one issue:
@Produces(
{
    MediaType.APPLICATION_JSON + "; charset=utf-8",
    MediaType.APPLICATION_XML  + "; charset=utf-8",
})

results in a header like:
Content-Type: application/xml;charset=utf-8

However some other code (a Python library) requires it to be like:
Content-Type: application/xml; charset=utf-8

(note the space between the ; and charset).
From what I can tell the space is optional, but the Python library (out of our control) requires it.
Any ideas on what I need to do to convince JAX-RS to spit out the space?


text:
Q: How to inject quasi quotes array I have an array of quasi quotes called definitions which I want to inject to the quasi quote tree.  How do I go about doing this?
private def generateDaoComponent(files: Array[File]) = {
    val file = createNewFile(compDirectory)

    val definitions = files.map(f => {
      val daoName = f.getName.replace(".java", "")
      val daoType = TypeName(daoName)
      val daoTerm = TermName(daoName)

      q"""def $daoTerm = getValueOrInstantiate($daoName, () => new $daoType(configuration))

       """
    })

    val tree = q"""
        package database.dao {
          import org.jooq.SQLDialect
          import org.jooq.impl.DefaultConfiguration
          import utility.StrongHashMap

          trait $componentType extends StrongHashMap[String, Dao] {
            this: DaoManager =>

            private lazy val configuration = new DefaultConfiguration().set(connection).set(SQLDialect.POSTGRES_9_4)

            ${definitions.foreach(f => q"${f}")}
          }
        }"""

    writeToFile(file, tree)
  }

A: This is some crazy late night coding, but I found it thanks to this website
3 approaches to Scala code generation
I noticed when it passed the $params array into the quasi quote it used two .. in front of the class constructor like this:
    val params = schema.fields.map { field =>
      val fieldName = newTermName(field.name)
      val fieldType = newTypeName(field.valueType.fullName)
      q"val $fieldName: $fieldType"
    }

    val json = TypeSchema.toJson(schema)

    // rewrite the class definition
    c.Expr(
      q"""
        case class $className(..$params) {

          def schema = ${json}

        }
      """
    )

There are two steps to the code I posted in the question to make this working.
1) Convert $definitions.toList to List
2) Add the two .. in front
So the final code looks like this:
    val definitions = files.map(f => {
      val daoName = f.getName.replace(".java", "")
      val daoType = TypeName(daoName)
      val daoTerm = TermName(new StringBuilder("get").append(daoName).toString())

      q"""def $daoTerm = getValueOrInstantiate($daoName, () => new $daoType(configuration))"""
    }).toList <--- HERE!

    val tree = q"""
        package database.dao {
          import org.jooq.SQLDialect
          import org.jooq.impl.DefaultConfiguration
          import utility.StrongHashMap

          trait $componentType extends StrongHashMap[String, Dao] {
            this: DaoManager =>

            private lazy val configuration = new DefaultConfiguration().set(connection).set(SQLDialect.POSTGRES_9_4)

            ..$definitions <-- AND HERE!

          }
        }"""


text:
Q: Cake php 2.10 login with http basic auth in controller action I'm working on a legacy project built with Cake PHP 2.10 and need to conditionally utilise HTTP basic auth in one of my controller's action. It's currently set up to utilise the identify method with the request from within the controller action and I need to get it to use HTTP basic auth.
I've set it up in my controller action but when passing my username and password in as http basic via Postman, $user is returning a boolean value of true always, regardless of whether I'm logged in or not.
What am I missing here?
public function appv6()
{
  header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
  header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");

  $this->Auth->sessionKey = false;
  $this->Auth->authenticate = array('Basic');
  $user = $this->Auth->login();

  var_dump($user);
  die;
}

A: You do not need to call $this->Auth->login() when Basic Auth is used. I think that at the time when you call it the user has already been authenticated.

Because basic and digest authentication don't require an initial POST or a form so if using only basic / digest authenticators you don't require a login action in your controller... Stateless authentication will re-verify the user's credentials on each request...

https://book.cakephp.org/2/en/core-libraries/components/authentication.html#using-digest-and-basic-authentication-for-logging-in


text:
Q: Object prototype interference with Easeljs I was setting up a little helper function like so:
if (!Object.prototype.__construct) {
Object.prototype.__construct = function() {
    if (typeof arguments[0] !== 'object' ||
        arguments.length === 0) return;
    for (var name in arguments[0]) {
        if (arguments[0].hasOwnProperty(name))
            this[name] = arguments[0][name];
    }
}}

if (!Object.prototype.__)
    Object.prototype.__ = Object.prototype.__construct;

It is invoked like such:
function Foo(props) {
    this.__(props); // or this.__construct(props);
    ...
}
var foo = new Foo({a:1,b:2,c:3});

As you can see, it just acts as a simple constructor. However when using it with EaselJS, specifically SpriteSheet() I get an error of Uncaught TypeError: Cannot call method 'slice' of undefined. Here is a snippet of code illustrating where the issue arises:
var ss = new SpriteSheet({
    images: ...,
    frames: {
        ...
    },
    animations: {
        walk: [0, 1, "walk", 8] // <-- Error caused here.
    }
});

So, is there a better way to go about writing an Object prototype like this, which will not cause a (presumably) clash with Easel? Or possibly a better way altogether? (Native?). Thanks.


text:
Q: Run some script upon internet connection I have a HUAWEI BM632w WIMAX modem/router. I wonder is there any way to run some script upon modem connection to internet on remote host or at least send some signal for some where and let them know I am on again?
Imagine all PCs connected to internet using this modem are off and only our modem is on and running.

A: You can run an IM client on the system, most of them can indicate on-line status.

A: I couldn't find much info about HUAWEI BM632w but most of Huawei's devices run a very closed  software. Its pretty hard to have startup scripts with such devices.
My best guess to why you would want to do such a thing would be to find out the IP address that was assigned to this device, remotely so you could get in and do some stuff. Correct me if I'm wrong here.
See if this device has any options related to dynamic dns in the settings to help you out. I don't suppose you can get a static IP from the ISP with wireless internet. If you do end up having a dynamic dns or a static ip setup, you could have some kind of script somewhere on remote servers to periodically pool data / ping from that location to see if the device is online.


text:
Q: Add sound switch off/on button corona sdk I need help with adding sound off/on button to my game. In global variable lua file, I have the following:
local sounds = {}
sounds["select"] = audio.loadSound("sounds/select.mp3")
sounds["score"] = audio.loadSound("sounds/score.mp3")
G.playSound = function(name)
    if sounds[name] ~= nil then
        audio.play(sounds[name])
    end
end

In games.lua file, I call the function as:
utils.playSound("score")

I have a soundon.png and soundoff.png files both in a sprite sheet (not sure if that is a good idea), all I am trying to implement is when you click the sound button, all sounds stops and it displays the soundoff image, vice versa.
Thanks

A: I personally wouldn't use a sprite sheet. Just load both images and toggle their "isVisible" field. Then toggle a variable which would stop your sounds. Try something like this.
myGlobalSoundToggle = true
local image = display.newImage("soundon.png")
local image2 = display.newImage("soundoff.png")
image2.isVisible = false

local function onTap( self, event )
    image.isVisible = ~image.isVisible
    image2.isVisible = ~image2.isVisible
    myGlobalSoundToggle = image.isVisible
    return true
end
image:addEventListener( "tap", onTap )

Now that we have our buttons working, we need to toggle the sound on and off.
local sounds = {}
sounds["select"] = audio.loadSound("sounds/select.mp3")
sounds["score"] = audio.loadSound("sounds/score.mp3")
G.playSound = function(name)
    if (sounds[name] ~= nil) and (myGlobalSoundToggle) then
        audio.play(sounds[name])
    end
end


text:
Q: Sort one column ascending and another column descending And by strange, I probably mean that it's intended behavior, but I don't understand why, nor how to fix it.
The task is to sort based on column 5, and then column 4.
grep -w RockDoveHPG_Transcript_21  xaa.blast| sort  -gk5,5 -gk4,4

which gives me
RockDoveHPG_Transcript_21   XM_004941221.2  70.588  17  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  82.353  17  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  68.182  22  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  80.000  25  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  57.692  26  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  70.588  34  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  100.000 77  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  77.778  18  2.46e-80
RockDoveHPG_Transcript_21   XM_004941221.2  89.474  19  2.46e-80
RockDoveHPG_Transcript_21   XM_004941221.2  70.000  20  2.46e-80
RockDoveHPG_Transcript_21   XM_004941221.2  71.429  21  2.46e-80
RockDoveHPG_Transcript_21   XM_004941221.2  72.000  25  2.46e-80
RockDoveHPG_Transcript_21   XM_004941221.2  72.727  33  2.46e-80
RockDoveHPG_Transcript_21   XM_004941221.2  94.737  76  2.46e-80
...
RockDoveHPG_Transcript_21   XM_004941221.2  78.947  19  1.56e-43
RockDoveHPG_Transcript_21   XM_004941221.2  71.429  21  1.56e-43
RockDoveHPG_Transcript_21   XM_004941221.2  83.544  79  1.56e-43

Col 5 sorts just fine, but ideally I'd like Col 4 sorted highest to lowest. Right now it's low to high. Ah, that sounds like I need the -r flag..
grep -w RockDoveHPG_Transcript_21  xaa.blast| sort  -gk5,5 -r -gk4,4

Now Col 5 is sorted in the opposite direction, but Col 4 is good.
RockDoveHPG_Transcript_21   XM_004941221.2  83.544  79  1.56e-43
RockDoveHPG_Transcript_21   XM_004941221.2  71.429  21  1.56e-43
RockDoveHPG_Transcript_21   XM_004941221.2  78.947  19  1.56e-43
RockDoveHPG_Transcript_21   XM_004941221.2  68.750  16  1.56e-43
RockDoveHPG_Transcript_21   XM_004941221.2  86.667  15  1.56e-43
RockDoveHPG_Transcript_21   XM_004941221.2  85.526  76  6.22e-44
...
RockDoveHPG_Transcript_21   XM_004941221.2  100.000 77  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  70.588  34  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  57.692  26  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  80.000  25  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  68.182  22  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  82.353  17  4.17e-86
RockDoveHPG_Transcript_21   XM_004941221.2  70.588  17  4.17e-86

So basically it seems like the -r flag is not applied column-wise.. Reversing order of 1 sorted column reverses the order of the other..
What I'd like, is to have
RockDoveHPG_Transcript_21   XM_004941221.2  100.000 77  4.17e-86

returned at the top, which I think should be accomplished by sorting Col5 lowest to highest and then Col 4 highest to lowest.

A: By adding -r the way you did, it is being treated as a global option. From info sort:

A position in a sort field specified with '-k' may have any of the
  option letters 'MbdfghinRrV' appended to it, in which case no global
  ordering options are inherited by that particular field.

Note the phrase "appended to it" i.e. to reverse only field 4, use -gk4,4r

A: use
grep -w RockDoveHPG_Transcript_21  xaa.blast| sort  -gk5,5 -gk4,4r

Notice the r at the end.


text:
Q: jQuery not let me submit all inputs of a form after the .append() I am adding number of inputs to my html form using jQuery .append(). I am trying to submit inputs using arrays but it does not recognize the appended input fields. If I append those statically it will work:
The input fields look like this:
<form action="http://localhost:8888/xxx/action.php" method="post" id="form">

                            <input type="text" class="qnaQ form-control" id="qnaQ" name="qnaQ[]">

                                <input type="text" class="qnaOpt1 form-control" id="qnaOpt1" name="qnaA1[]">

                                <input type="text" class="qnaOpt2 form-control" id="qnaOpt2" name="qnaA2[]">

                                <input type="text" class="qnaOpt3 form-control" id="qnaOpt2" name="qnaA3[]">

                                <input type="text" class="qnaOpt4 form-control" id="qnaOpt4" name="qnaA4[]">

                                    Correct Answer:

                                    Answer

Option1

Option2

Option3

Option4

The script that adds more field:

The button that submits the form to the php:
<button type="submit" class="btn btn-default saveTraining" id="saveTraining">
        Save
    </button>

A: try to add form attribute to the input tag with the form id :
<input ... form="form-id">

A: You shouldn't use the same id more than once.
What I could understand there, when you append a new question, the ids and names of the texts are the same, and with this, the post its not going to recognize all the values.


text:
Q: Issue comparing Japanese characters I am struggling to use HTML::TokeParser
to parse an HTML document that contains Japanese characters.
Here is my code:
use utf8;

use Encode qw(decode encode is_utf8);
use Encode::Guess;
use Data::Dumper;
use LWP::UserAgent;
use HTTP::Cookies;
use Cwd;
use HTML::TokeParser;

my $local_dir = getcwd;

my $browser = LWP::UserAgent->new();

my $cookie_jar = HTTP::Cookies->new(
   file     => $local_dir . "/cookies.lwp",
   autosave => 1,
);

$browser->cookie_jar( $cookie_jar );

push @{ $browser->requests_redirectable }, 'POST';
$browser->requests_redirectable;

my $response = $browser->get("http://www.yahoo.co.jp/");
my $html = $response->content;
print $html;
utf8::decode($html);

my $p = HTML::TokeParser->new( \$html );

# dispatch table with subs to handle the different types of tokens

my %dispatch = (
   S  => sub { $_[0]->[4] }, # Start tag
   E  => sub { $_[0]->[2] }, # End tag
   T  => sub { $_[0]->[1] }, # Text
   C  => sub { $_[0]->[1] }, # Comment
   D  => sub { $_[0]->[1] }, # Declaration
   PI => sub { $_[0]->[2] }, # Process Instruction
);

while ( my $token = $p->get_tag('a') ) {
        print $p->get_trimmed_text if $p->get_trimmed_text eq '社会的責任';
        print "\n";
}

This doesn't display anything on my terminal, but if I just do a print $p->get_trimmed_text then the output is OK.
Here are a few hexdump lines corresponding to print $p->get_trimmed_text:
0000000 490a 746e 7265 656e 2074 7845 6c70 726f
0000010 7265 81e3 e4ae 92ba 8fe6 e89b a8a1 a4e7
0000020 e3ba ab81 81e3 e3a4 8481 81e3 0aa6 9fe7
0000030 e5b3 9db7 81e9 e3bc 8982 9be5 e5bd 8586
0000040 a4e5 e396 ae81 83e3 e397 ad83 82e3 e3b4
0000050 ab83 83e3 e395 a182 83e3 e3bc 8c81 86e7
0000060 e68a ac9c 94e6 e6af b48f 320a e334 ab82
0000070 89e6 e380 ae81 b4e7 e885 8991 90e5 e68d
0000080 8089 82e3 e692 a597 b8e5 e3b0 8a82 82e3
0000090 e3b3 bc83 82e3 e4b9 95bb abe7 e38b a681
00000a0 81e3 e7a7 b9b4 bbe4 0a8b 83e3 e39e af82
00000b0 83e3 e389 8a83 83e3 e3ab 8983 82e3 e384
00000c0 8783 83e3 e38b bc83 82e3 e3ba ae81 81e3
00000d0 e58a 97be 81e3 e3aa af82 83e3 e3bc 9d83
00000e0 83e3 e9b3 8d85 bfe4 0aa1 a8e8 e88e 96ab
00000f0 bce4 e39a 8c80 83e3 e392 a983 83e3 e3aa
0000100 bc83 b0e6 e58f 9d8b 88e5 e3a9 8d80 3235
0000110 e525 9986 9ce7 4e9f 5745 e50a a7a4 98e9

It seems like the comparison does not work.
I can use only HTML::TokeParser because that's the only module installed on the server and I can't install anything else.

A: You expect your two calls to $p->get_trimmed_text to return the same string, but it returns a different token each time it's called. Replace
print $p->get_trimmed_text if $p->get_trimmed_text eq '社会的責任';

with
my $text = $p->get_trimmed_text;
print $text if $text eq '社会的責任';

You shouldn't assume the HTML is encoded using UTF-8. Replace
my $html = $response->content;
utf8::decode($html);

with
my $html = $response->decoded_content;

Also need to encode your outputs. One way is by adding the following:
use encode ':std', ':encoding(UTF-8)';

A: Please see ikegami's answer. Mine is just an alternate approach which does not address the actual issue with your code.

Unicode::Collate to the rescue!
Note that I added below in your code.
use Unicode::Collate;
use open qw/:std :utf8/;
my $Collator = Unicode::Collate->new();
sub compare_strs
{
    my ( $str1, $str2 ) = @_;
    # Treat vars as strings by quoting.
    # Possibly incorrect/irrelevant approach.
    return $Collator->cmp("$str1", "$str2");
}

Note: compare_strs subroutine will return 1 (when $str1 is greater than $str2) or 0 (when $str1 is equal to $str2) or -1 (when $str1 is less than $str2).
Below is the complete working code:
use strict;
use warnings;
use utf8;
use Unicode::Collate;
use open qw/:std :utf8/;
use Encode qw(decode encode is_utf8);
use Encode::Guess;
use Data::Dumper;
use LWP::UserAgent;
use HTTP::Cookies;
use Cwd;
use HTML::TokeParser;
my $local_dir = getcwd;
my $browser = LWP::UserAgent->new();
my $cookie_jar = HTTP::Cookies->new(
   file     => $local_dir . "/cookies.lwp",
   autosave => 1,
);
$browser->cookie_jar( $cookie_jar );
push @{ $browser->requests_redirectable }, 'POST';
$browser->requests_redirectable;
my $Collator = Unicode::Collate->new();
sub compare_strs
{
    my ( $str1, $str2 ) = @_;
    # Treat vars as strings by quoting.
    # Possibly incorrect/irrelevant approach.
    return $Collator->cmp("$str1", "$str2");
}
my $response   = $browser->get("http://www.yahoo.co.jp/");
my $html = $response->content;
#print $html;
utf8::decode($html);
my $p = HTML::TokeParser->new( \$html );

# dispatch table with subs to handle the different types of tokens
my %dispatch = (
   S  => sub { $_[0]->[4] }, # Start tag
   E  => sub { $_[0]->[2] }, # End tag
   T  => sub { $_[0]->[1] }, # Text
   C  => sub { $_[0]->[1] }, # Comment
   D  => sub { $_[0]->[1] }, # Declaration
   PI => sub { $_[0]->[2] }, # Process Instruction
);

my $string = '社会的責任';
while ( my $token = $p->get_tag('a') ) {
        my $text = $p->get_trimmed_text;
        unless (compare_strs($text, $string)){
          print $text;
          print "\n";
        }
}

Output:
chankeypathak@perl:~/Desktop$ perl test.pl
社会的責任


text:
Q: how to print RTC use Assembly interrupt vector 1ah I need to output an Interrupt 1h. (RTC).
But I don't know how to print RTC in console. Should I use interrupt 10h, or is there another way?
I already tried to find some in google, and I applied the interrupt 10 directly as below.
mov ah 0x02
int 0x1a

But it's not working. I know that the code is poor.
Please give me some help. If you can make example for me, I'd really appreciate it.

A: Looking at docs for int 0x10, we see a number of functions.  You didn't specify which you tried to use, but let's look at ah=0x0e:
Expects: AH    0eH
         AL    character to write
         BL    (graphics modes only) foreground color number

The 'character to write' is the ascii value of the character we want to display.  So for example if you want to write the character '7', you would put the ascii value for it (55 aka 0x37) into al.  Just putting 0x7 into al would be the ascii character for BEL (and would make the speaker beep).
So, what if you want to print the number 1234?  Well, you would need to call this function 4 times, with each of 49, 50, 51, 52.
I know, you're wondering if there is some way to output a string?  Sure.  For example there is INT 0x10, ax=0x1300.  However, you STILL need to turn 1234 into the appropriate ascii characters, then call the BIOS function to output the string you have created.
Isn't there some sort of printf("%d") that does that conversion for me?  Not in the BIOS.  BIOS functions are designed to be very low level.  That's (part of) WHY there are operating systems, C runtime libraries, etc, so that people don't have to write all this junk.
If you don't want to write such a function yourself, there are asm 'libraries' out there that have collections of routines for performing this type of thing.


text:
Q: What is the inverse of the following function? What is the inverse function of $ y=x^3+x$? thanks

A: According to Wolfram Mathematica, the equation $x^3+x=y$ is solved by
$$
x=\frac{\sqrt[3]{\sqrt{3} \sqrt{27 y^2+4}+9 y}}{\sqrt[3]{2}
   3^{2/3}}-\frac{\sqrt[3]{\frac{2}{3}}}{\sqrt[3]{\sqrt{3} \sqrt{27 y^2+4}+9 y}}.
$$

A: I get $x= y-y^3+3y^5-12y^7+55y^9-273y^{11}+-...$ where the coefficients are given by http://oeis.org/A001764 with alternating signs.
This is of course convergent up to the point where the closed form solution has its poles. The reference shows that, as a generating function, the coefficients have nice closed forms in terms of binomial coefficients.


text:
Q: KML LineString Length Using MSVS C#, I'm creating a KML file. For the sake of simplicity, assume that it has 2 Point placemarks with name tags A and B, respectively. The third placemark is a LineString using the coordinates from the points, with a name tag "A > B". I want the description of this placemark to say "Distance: xxx km", where xxx is the distance between A and B.
Is there a KML or Google Earth tag that I can write to the KML file that will output the distance when the file is loaded into Google Earth and I click on the line? Better yet, can I keep track of these as the app generates the KML file or in the KML file itself so that the document can have a description that has the total distance of all LineStrings?
Thanks.

A: After posting this, I came across a Vicenty formula written in Java that does what I want. It was a simple matter to port it to C#.
It can be found at https://www.neovasolutions.com/2019/10/04/haversine-vs-vincenty-which-is-the-best/
It's a shame a forum designed to help developers would have someone downgrade a question without even bothering to post a response that might be of use, even if it's a link to where such a question was answered. If this was an admin who did this, kindly delete my account—I certainly don't need the bigotry and scrutiny. In the future, I'll try to find my answers elwewhere.


text:
Q: Value of java.lang.String cannot be converted to double I have a PHP web service whill pulls data out of a MySQL database.
I have an Android app which calls the service.
Locally on my WAMP Server everything works fine but I just uploaded the data/service to a domain and testing against that.
I am getting this error:
org.json.JSONException: Value  at Latitude of type java.lang.String cannot be converted to double

From this line of code:
double latitude = thisVenue.getDouble(TAG_LATITUDE);

And the value (taking from the log via Android Studio) which causes this error is:
"Latitude":"51.05279"

I cannot see why that value cannot be converted to a double. Locally my app can parse the same dataset no problem so I presume it has something to do with how it is stored/retrieved?
Edit: Here is one of the objects returned in JSON, notice all values have quotes
{"VenueID":"4","ListingID":"19","Name":"TempName1","Location":"207 10A St NW","DayOfWeek":"Mon","Featured":"0","FeaturedDistanceRange":"0","Latitude":"51.05279","Longitude":"-110.087509","StartHour":"4","StartHourType":"pm","StartMinute":"0","EndHour":"7","EndHourType":"pm","EndMinute":"0"}

And I format it as JSON like so:
    header("Content-type: application/json");
    print(json_encode(array('venues'=>$data)));

A: As the data from the server is not a double, u must use as this
double latitude = Double.valueOf(thisVenue.getString(TAG_LATITUDE));

A: Check you are getting a valid double back from the getDouble() method (the compiler doesn't think you are. If the following compiles and throws a NumberfFormatException at runtime then you know you're not getting a valid double.
And "Latitude":"51.05279" doesn't look like a parseable double, "51.05279" would be fine.
double latitude = Double.parseDouble(thisVenue.getDouble(TAG_LATITUDE));


text:
Q: Dagger 2: Inject child class based on logic Using Dagger 2 in my android with MVP pattern, and struggling a little with some concepts.
Let's say I have a presenter DashboardPresenter, I am injecting it when I need it in an activity or other presenters, by using:
@inject
DashboardPresenter presenter;

or in the constructor of other presenters:
@inject
public AccountPresenter(DashboardPresenter presenter) {
    //init
}

Now I'm not very sure how it works, but I want to do the following:
Let's say I create a BaseDashboardPresenter which will be the parent
And I create 2 children for it: NormalDashboardPresenter and ProDashboardPresenter both extends from it.
When I want to use it in an activity or another presenter, I inject the Base presenter by calling
@inject
BaseDashboardPresenter presenter;

And I override the @inject behavior, to inject one of the children based on a boolean.
So something like this:
//in BaseDashboardPresenter
override inject() {
    if(Utility.checkIfUserIsPro()) {
        inject ProDashboardPresenter();
    } else {
        inject NormalDashboardPresenter();
    }
}

so from my activity I just call the abstract methods in the Base class, and the difference is only which child is injected.
Is this possible?
Happy to provide more clarification if needed.

A: To do this, you should add in your module something like this:
@Provides
public BaseDashboardPresenter provideDashboardPresenter(OtherPresenter presenter) {
    if (Utility.checkIfUserIsPro()) {
        return new ProDashboardPresenter();
    } else {
        return new NormalDashboardPresenter(presenter);
    }
}

A: Contrary to the other answer I believe that your modules should not include any logic. That's just not what one would expect.
Also, how would your @Provides method look if one variant needs A, while the other depends on B? Now you need to declare dependencies that you don't need and it just gets more confusing from here on.

Instead you should create one module for every option and include the correct module in your component.
// module providing pro version
componentBuilder.addPresenterModule(new ProModule());

// or a default one
componentBuilder.addPresenterModule(new DefaultModule());

That way wherever you build your component you get to decide what's supposed to be in it. An even more dedicated approach would be to use 2 completely different components where each component uses different modules etc. This might make sense for more complex projects, but in your case it seems that modules would be enough.


text:
Q: Architecting MVC application with RESTul Services We are developing a ASP.NET MVC application and want to use Web API to handle the business functionality.  In addition we also have integration with Dynamics AX and Dynamics CRM products.  So, in essence I was thinking to develop the following components :

*

*To build a RESTFul Service that communicates with AX (through SOAP)
and return a Data Transfer Object.

*To build a RESTFul Service that
communicates with CRM (again through SOAP) and return a Data
Transfer Object.

Now my question is, for instance to load data into an Order Screen (which need data from AX and CRM),
a. Use the controller to make calls to the RESTFUL Services and then use a Model object to pass the data to the screen.
(or)
b. Do nothing in the controller, but use AJAX calls from the Razor to get data from the RESTFul services and load data into the screen.

Would appreciate, If anyone could throw some light on the best practice to adopt (with respect to architecting in such a scenario using MVC & RESTFUL services)?

A: If you are calling external RESTful services, you will need to create HTTP requests via POST or GET and handle the response returned by the requests appropriately. If the data returned is XML, you'll need to consume the XML using an XML document parser. If the data returned is JSON, you could use dynamic parsing like shown here: Deserialize JSON into C# dynamic object?
This is a very nice way to deal with JSON as it provides a mechanism similar how you would access a JSON object in JavaScript.
Here is some code that I use with my web APIs:
public class Base
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string UserAgent { get; set; }
    public string ContentType { get; set; }
    public CookieCollection Cookies { get; set; }
    public CookieContainer Container { get; set; }

    public Base()
    {
        UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0";
        ContentType = "application/x-www-form-urlencoded";
        Cookies = new CookieCollection();
        Container = new CookieContainer();
    }

    public Base(string username, string password)
    {
        Username = username;
        Password = password;
        UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0";
        ContentType = "application/x-www-form-urlencoded";
        Cookies = new CookieCollection();
        Container = new CookieContainer();
    }

    public string Load(string uri, string postData = "", NetworkCredential creds = null, int timeout = 60000, string host = "", string referer = "", string requestedwith = "")
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.CookieContainer = Container;
        request.CookieContainer.Add(Cookies);
        request.UserAgent = UserAgent;
        request.AllowWriteStreamBuffering = true;
        request.ProtocolVersion = HttpVersion.Version11;
        request.AllowAutoRedirect = true;
        request.ContentType = ContentType;
        request.PreAuthenticate = true;

        if (requestedwith.Length > 0)
            request.Headers["X-Requested-With"] = requestedwith; // used for simulating AJAX requests

        if (host.Length > 0)
            request.Host = host;

        if (referer.Length > 0)
            request.Referer = referer;

        if (timeout > 0)
            request.Timeout = timeout;

        if (creds != null)
            request.Credentials = creds;

        if (postData.Length > 0)
        {
            request.Method = "POST";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);
            request.ContentLength = data.Length;
            Stream newStream = request.GetRequestStream(); //open connection
            newStream.Write(data, 0, data.Length); // Send the data.
            newStream.Close();
        }
        else
            request.Method = "GET";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Cookies = response.Cookies;
        StringBuilder page;
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            page = new StringBuilder(sr.ReadToEnd());
            page = page.Replace("\r\n", ""); // strip all new lines and tabs
            page = page.Replace("\r", ""); // strip all new lines and tabs
            page = page.Replace("\n", ""); // strip all new lines and tabs
            page = page.Replace("\t", ""); // strip all new lines and tabs
        }

        string str = page.ToString();
        str = Regex.Replace(str, @">\s+<", "><"); // remove all space in between tags

        return str;
    }
}

I'm working on an API for interacting with Xbox Live, PSN, and Steam data. Each service has their own structure and this is the base class that I use for each service. However, I'm not going to go into specifics on how to get data from each of those services here.


text:
Q: Is there a way to import strings from a text file in javascript, meteor? I have a programm where I need to have long multi line strings. It's a pain to store them in the .js document, because js doesn't have multi line strings and I end up having a twice as long as the screen width line looking as ugly as "This is an example.\n"
Is there a way to have a txt file, from where I can import strings with new lines (or at least just import strings)?

A: There is a Meteor Assets object that allows you to read files in the private directory of your app, in the following way for example for text files.
Assets.getText("foo.txt", function (err, res) { ... });

See full documentation: http://docs.meteor.com/#assets

A: Previous answer works only for public files. If you want to access file data that is visible only on the server you should probably use 'fs' npm module. It's described in details here: http://www.eventedmind.com/posts/meteor-file-uploader-part-2-server-side-save

A: The meteor-yaml package makes this easy - it automatically loads any .yaml files in your project, parses them into JavaScript objects, and makes them available in YAML.data.
In my application I have some code outside of the meteor app that needs the same settings, so I prefer to have the config file outside of the meteor project directory.  Then I load the file like this:
var fs = Npm.require('fs');
fs.readFile('<path to file>.yaml', 'utf8', function(err, data) {
  if(err) {
    //Throw exception if the file is missing
    throw new Error("Missing config file")
  }
  else {
    //Read the file into a JavaScript object
    config = YAML.parse(data);
  }
});

Unfortunately, the meteor-yaml package is a little out of date with how the meteor team wants node packages to be loaded now, so if you're using a recent version of meteor the package won't work out of the box.
I filed a bug about this, but in the meantime to get around it I installed it as a private package, as opposed to installing it from atmosphere, and fixed the bug.  To do this:

*

*Clone the repo under your projects packages/ directory

*Comment out the Npm.require lines.

*Add a call to depends:
Npm.depends({yamljs: "0.1.4"});

*Run meteor.  Meteor will detect the meteor-yaml private package and install the dependencies.


text:
Q: Directory.GetFiles() returns full path I want to return the files that are  images, inside a particular directory. I want to create the image path like this
  string[] ImageNames = Directory.GetFiles(path);

        string tds="";
        for (int i = 0; i < ImageNames.Length; i++)
        {
          tds += "

 	";
        }

but it returns the physical path of the file on the disk. How should I do this??

A: You can use Path.GetFileName:
string[] ImageNames = Directory.GetFiles(path)
                                    .Select(p => Path.GetFileName(p)).ToArray();

This will produce a list with only the names of the files.

A: Rather than using the Directory class I would use DirectoryInfo then you can do this;
 string[] fNames = new DirectoryInfo(dirPath).GetFiles("*.png").Select(x => x.FileName).ToArray();

The DirectoryInfo version of GetFiles returns FileInfo objects rather than the file paths as strings so you can do a lot more the with the results. I happen to have a select which sort of nullifies that by just projecting a the FileName for each FileInfo instance returned by GetFiles but if you needed to do more with the files you could remove that then loop over the FileInfo objects.
Also, I'm using an overload that has a pattern which will make it easy to ignore your non image files.
DirectoryInfo docs; http://msdn.microsoft.com/en-us/library/8he88b63.aspx


text:
Q: Use mongoose query to get only a subdocument I have a similar datastructure as this:
var GrandGrandChild = mongoose.Schema({
    attribute: String,
    id: Number
});

var GrandChild = mongoose.Schema({
    children: [GrandGrandChild],
    id: Number,
    irrelevantAttribute: String
});

var Child = mongoose.Schema({
    children: [GrandChild],
    id: Number,
    irrelevantAttribute2: String
});

var Parent = mongoose.Schema({
    children: [Child],
    id: Number,
    irrelevantAttribute3: String
});

var GrandParent = mongoose.Schema({
    children: [Parent],
    id: Number,
    irrelevantAttribute4: String
});

These are a lot of collections with subdocuments in them.
Note that the ID's are unique to their siblings, but not unique to all elements with that same schema.
So one grand parent can have an parent with id 0, and another grandparent can also have a parent with id 0. but one grandparent can not have 2 parents with id 0.
The only schema that gets saved is the GrandParent schema, and mongoose/mongodb makes a nice big single document of all the data of this grandparent. (Exactly what i am looking for)
So here is my issue: I have a GrandParent ID, Parent ID, Child ID, GrandChildID and GrandGrandChild ID, and i want to somehow get only the GrandGrandChild object to which all these ID's are pointing.
The ugly way would be to, but currently the only way i can get to work, is to make a query that gets this big document of GrandParent, and manually loop through all arrays to find the right Parent, then loop again to find the right child, then loop again to find the right grandchild, then loop again and find the grandgrandchild im needing here.
My question is, how would i compose a query in mongoose that either returns  only the grandgrandchild document, or the grandparent document with only the children attribute included, and in that children attribute only the parent object included that refers to the child object that refers to the grandchild object that refers to the grandgrandchild object, allowing the following with the result:
GRANDPARENT  PARENT      CHILD      GRANDCHILD   GRANDGRANDCHILD
grandparent.children[0].children[0].children[0].children[0].attribute;

I hope someone can help me on this query, as far is i got is this:
GrandParentModel.findOne(
    {
        "id" : 0,
        "children.id" : 0,
        "children.children.id" : 0,
        "children.children.children.id" : 0,
        "children.children.children.children.id" : 0
    },
    {"children.children.children.children.$" : 1}, callback);

The problem with this query is that the unnessicary siblings arent trimmed away.
I hope someone can help me out.
Hylke Bron

A: it has been some time since I asked this question, but I think I found a rather elegant way of working with these kind of structures.
In this case I'll show how it works with only GrandParent, Parent and Child.
Instead of storing a list of subdocuments in each document (GrandParent.children, Parent.children), I created an unique identifier of the following structure:
Child.referenceId = {
    grandparent: "some key to the grandparent of the parent",
    parent: "some key to the parent",
    child: "key of this child"
};

Parent.referenceId = {
    grandparent: "some key to its grandparent",
    parent: "key of this parent"
}

GrandParent.referenceId = {
    grandparent: "key of this parent"
}

This creates a hierarchy of GrandParent > Parent > Child.
The models would be something like the following:
var idStructure = {
    grandparent: { type: String, required: true },
    parent: { type: String, required: false },
    child: { type: String, required: false }
};

var GrandParent = mongoose.Schema({
    id: idStructure,
    irrelevantAttribute: String
});

var Parent = mongoose.Schema({
    id: idSructure,
    irrelevantAttribute: String
});

var Child = mongoose.Schema({
    id: idStructure,
    irrelevantAttribute: String
});

Notice that a Parent doesnt directly knows its parent, for they are not stored as subdocuments. Yet there still is a connection between Parent and Child, through the referenceId.
When searching for the whole familytree of a GrandParent, one would simply execute 3 queries, and then connect them correctly:
// First find all children which belong to the grandparent
Child.find({"id.grandparent" : "some key to the grandparent"})
.exec(function(err, children)
{
     if(err)
         return;

     Parent.find({"id.grandparent" : "some key to the grandparent"})
     .exec(function(err, parents)
     {
         if(err)
             return;

         // Loop through the parents and children to connect them before returning to a client
         for(var i = 0; i < parents.length; i++)
         {
             var parent = parents[i];
             parent.children = [];
             // loop through the children to check if they belong to the current parent
             for(var j = 0; j < children.length; j++)
             {
                 var child = children[j];
                 if(parent.id.parent == child.id.parent)
                     parent.children.push(child);
             }
         }

         // After filling the children into the parents, get the grandparents and do the same for the parents and grandparents as done for the children and parents.
        GrandParent.find({"id.grandparent" : "some key to the grandparent"})
       .exec(function(err, grandparents)
       {
           // TODO: the same as done above (two loops, one loops the grandparents, other loops the parents
           // Once this is finished, we have a filled grandparent
       });

     });
});

The code above would result in just ONE grandparent, filled with parents, which are filled with children.
The reason no more grandparents would be found is because the id of the grandParent should be unique, for the referenceId of the grandparent only has a grandparent property.
I hope i made my point clear, because through this method, one can easily search for one specific child, easily get its parent through the reference id, and its grandparent also through the reference id.
It might be a bit complex, but once you figure the method out for yourself, its all kinda straight forward.
Hylke

A: Is very difficult to get this kind of things work in a clean way.
I didn't find a clean solution on this topic, but maybe I can help you with the looping thing.
You can avoid the loop using:
var doc = parent.children.id(id); Finding a sub-document
I hope this help you.
Regards,
Sebastian.

A: this worked for me
      model.find({_id:args.id},{ commentList: { $elemMatch: { _id: todo.commentList[todo.commentList.length-1] } } },(err, todos) => {
         if (err) reject(err)
         else resolve(todos)
         console.log(todos);
      })

$elemMatch (projection)


text:
Q: Excel/CSV - putting a single quote to keep leading zeros does not work on a Mac Other suggested to keep the leading zeros in Excel/CSV, I can just add the single quote character. However, this does not work on a Mac properly. The single quote shows up, which is something that I do not want.
Please see image for more details.

https://social.msdn.microsoft.com/Forums/en-US/aae07b39-865f-4c68-a07f-7cad2dfd6733/how-do-i-open-csv-using-excel-without-deleting-leading-zeros?forum=isvvba

A: I can just use "=""00100""" to keep the leading zeros.


text:
Q: How to count average number of courses taught per staff member? SQL I am learning SQL now and I have a DB table COURSE as follow:
CREATE TABLE COURSE (COURSE_ID CHAR(6),
 COURSE_TITLE CHAR(20),
 STAFF_ID CHAR(3),
 SECTION NUMBER(2));

And another table STAFF:
CREATE TABLE STAFF (STAFF_ID CHAR(3),
 STAFF_NAME CHAR(20),
 GENDER CHAR(6),
 DEPARTMENT CHAR(20),
 BOSS_ID CHAR(3)
 SALARY NUMBER(8,2));

My Problem is I want to calculate the average number of courses taught per staff member.
I want to have some inspiration and tips on this.
Thanks a lot for help.

A: SELECT  COUNT(DISTINCT S.STAFF_ID) / (COUNT(C.STAFF_ID) * 1.0) FROM STAFF S LEFT JOIN COURSE C ON S.STAFF_ID = C.STAFF_ID;

The first count gives us the number of staff members, the second gives us the number of courses currently being tought by all the staff members. Dividing those two we get the number of courses per staff member.

A: select st.staff_id, st.staff_name, count(crs.course_id)
from staff st inner join course crs on
  st.staff_id = rs.staff_id
group by st.staff_id, st.staff_name;

this query will fetch the staff_name,staff_id along with the number of courses that each staff teaches.


text:
Q: voltage level handled using optocoupler I want to program at89c2051 chip. I am referring circuit diagram where the optocoupler is used to handle the 2 voltage levels (+12V and +5V).
i didn't understand how Pin A0 and A1 will control the voltage level. Here is the optocoupler circuit


text:
Q: find values with a list of search parameters In my example I'm having problems to add my search results to one list. I have to display multiple students wHich are in different locations. I am having problems with .ToList() in foreach statement. It only displays my students from last location.
Below is my code:
public void Search(IEnumerable<string> Location)
{
    Location.ToList();

    foreach (var l in Location)
    {
        var students = from s in db.Students
                       select s;

            students = students.Where(s => s.City.Contains(l));

        var searched = students.ToList();
        int custIndex = 1;
        Session["Students"] = searched.ToDictionary(x => custIndex++, x => x);
        ViewBag.TotalNumberStudents = searched.Count();
    }
}

A: The problem likely is caused because you keep replacing your Session["Students"] and ViewBag.TotalNumberStudents:
Session["Students"] = searched.ToDictionary(x => custIndex++, x => x);
ViewBag.TotalNumberStudents = searched.Count();

Hence, only the last searched in the end got passed.
Try to accumulate the result, then pass them at once to Session["Students"] and ViewBag.TotalNumberStudents

A: There are few problems in your code, custIndex is defined inside the loop and Session variable overwrites by next iteration, hence you notice only last seached results in the session.
You could just do this.
int custIndex =1;
Session["Students"] = Location.SelectMany(l=> db.Students.Contains(l))
                              .ToDictionary(x=>custIndex++, x=>x);

ViewBag.TotalNumberStudents = searched.Count();


text:
Q: Wordpress: How to prevent auto generation imgs with all possible demnisions Wordpress auto generates images with all possible demnisions..
For example: generate thumbnail, medium, large etc
How I can make wordpress produce images only on demant.
For example if I want only have the thumbnail size for one image, then the only images which are created will be only the original size and the thumbnail size. For other image, maybe I will want only the original kai medium size..
Is it possible to do something like that?
I don't talk about unset function..
Sorry for my English!

A: That's how WordPress works, it's native behaviour, it generates all possible thumbnails of the image so it can be loaded in any size when needed. In other words, thumbnails are generated when uploading image and not when showing in (on-demand concept).


text:
Q: java documentlistener I'm trying to call method after changing text of JTextField.
textField.getDocument().addDocumentListener(new DocumentListener()
        {

            public void changedUpdate(DocumentEvent arg0)
            {
                System.out.println("IT WORKS");
                panel.setPrice(panel.countTotalPrice(TabPanel.this));
            }
            public void insertUpdate(DocumentEvent arg0)
            {

            }

            public void removeUpdate(DocumentEvent arg0)
            {

            }
        });

When I call this method at another ActionListener, it works ok. But when I change text in text field, nothing happens. Even println. Any suggestions?

A: The problem solved. changedUpdated method called only when other atributes (font, size, but not text) changed. To call method after every change of text, I should put the call into insertUpdate and removeUpdate methods. This way:
textField.getDocument().addDocumentListener(new DocumentListener()
        {

            public void changedUpdate(DocumentEvent arg0)
            {

            }
            public void insertUpdate(DocumentEvent arg0)
            {
                System.out.println("IT WORKS");
                panel.setPrice(panel.countTotalPrice(TabPanel.this));
            }

            public void removeUpdate(DocumentEvent arg0)
            {
                System.out.println("IT WORKS");
                panel.setPrice(panel.countTotalPrice(TabPanel.this));
            }
        });

A: Try using an ActionListener:
textField.addActionListener(this);

...
public void actionPerformed(ActionEvent evt) {
   String s = textField.getText();
   System.out.println(s);
   ...
}

A: I found this solution the fastest:
new JTextPane().addActionListener(new Key());

class Key extends KeyAdapter{
private static final Object lock = new Object();
        private static int keydiff=0;
        public void keyReleased(KeyEvent e) {
            switch(e.getKeyCode())
            {
                //IGNORE FUNCTIONAL KEYS
                case 38 :
                case 39 :
                case 37 :
                case 40 :
                case 17 :
                case 157 :
                case 10 : break;
                default : keydiff++;
            }

            if(keydiff!=0)
            {
              synchronized(lock){
                  keydiff=0;
                  //EVENT FIRED HERE
              }
            }
        }
    }

It's much faster than:
.getDocument().addDocumentListener( .... changeUpdate())

A: Here is another solution to your problem. Instead of having to repeat the same code under each method, you could create a method and call that method for changedUpdate, insertUpdate, removeUpdate.
textField.getDocument().addDocumentListener(new DocumentListener()
    {

        public void changedUpdate(DocumentEvent arg0)
        {
            printMyLines();
        }
        public void insertUpdate(DocumentEvent arg0)
        {
            printMyLines();
        }

        public void removeUpdate(DocumentEvent arg0)
        {
            printMyLines();
        }

        private void printMyLines()
        {
            System.out.println("IT WORKS");
            panel.setPrice(panel.countTotalPrice(TabPanel.this));
        }
    });


text:
Q: JavaFX Freezes Mac When Running Second Time The following completely freezes my MacBook Pro when I run it the second time (both in Eclipse and directly from the command-line). First time the GUI is displayed and the app runs as expected, but when I then stop and re-run it exactly the same way it freezes the computer completely.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(final Stage primaryStage) throws Exception {
        final Scene scene = new Scene(new StackPane());

        primaryStage.setTitle("Hello Crash!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(final String... arguments) {
        launch(arguments);
    }
}

Anyone have any idea? I'm thinking the solution may be some combination of –launcher.secondThread, -XstartOnFirstThread, -XstartOnSecondThread like when running a Swing GUI with OSGI on a Mac, but I haven't had any success.
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)

A: I had the same thing and found out that it is a problem with OS X switching graphic cards - i fixed the problem by installing gfx.io and forcing OS X to one graphic card


text:
Q: Is it possible to remove nested directories "/runner_id/0/company_name" from a Gitlab CI build path? I have an existing directory structure on a machine and want to configure Gitlab CI to clone/fetch repos to specific paths.
I've managed to change the builds_dir property in the config.toml file to start in the correct place, but Gitlab adds extra nested folders by default.
So I set:
builds_dir = "/Users/myUser/Development/projName"

and when Gitlab CI clones the repo, it adds
"/555555bb/0/orgName"

so I end up with:
"/Users/myUser/Development/projName/555555bb/0/orgName/projName"

Is there a way in the Gitlab config file to remove the extra sub-directories, or is my only option to move the files around after the clone/fetch is complete?

A: Because of how Gitlab runners work you need to copy the files to the appropriate locations.
Since runners can handle multiple projects, they need to differentiate them in some way and this is where /555555bb/0/orgName part comes in.
You can define in your project-specific runner config where those files need to be copied to (a simple copy command will suffice).

A: I solved it by creating a symbolic link between the repository used by the gitlab runner and the repository I am wishing to use for the deployment of the application.


text:
Q: how to force rack:session + sinatra to read "rack.session" from params instead of cookies I am dealing with oauth 1.0 (twitter and flickr). Website works at port 80 and oauth server works at port 8080
Algorithm:

*

*send ajax request to oauth server to check if user have valid access_token

*open authorization window if user have no access_token or access_token is expired

*save access_token in user's session at the oauth server

*send sharing data to the oauth server

It uses sinatra + rack:session + rack::session::sequel + sqlite to store sessions. It sends Set-Cookie: rack.session=id in each response
I am using 2 types of request: crossdomain ajax with jquery and usual request with window.open. I have a big security problem passing cookies to crossdomain ajax request.
No matter that server's response headers contains

Access-Control-Allow-Headers: *

chromium will throw security error:

Refused to set unsafe header "Cookie"

I want to avoid this problem by passing rack.session=id to post data and load it:
before "/twitter/connect.json" do
  session = Rack::Session::something(params["rack.session"])
end

But I cant find in documentation how to do this

A: Rack::Session::Abstract::ID has an option called cookie_only that allows the session id to be passed in via the params. However, it defaults to true, and most session middleware implementations don't bother to override it.
Your best bet is probably to monkey patch Rack::Session::Abstract::ID to default cookie_only to false.
Rack::Session::Abstract::ID::DEFAULT_OPTIONS.merge! :cookie_only => false


text:
Q: Invoking an Obj-C class method named `init` from Swift I'm using a 3rd party library in my Swift 4.1 code that has an Obj-C header file with a class level method named init().  When I try to invoke it, the compiler gets confused and says it's ambiguous whether I want to use an instance initializer or this static init method, like so:
My3rdPartyClass.init() // Error: Ambiguous use of 'init()'
In the My3rdPartyClass.h file:
@interface My3rdPartyClass : NSObject

+(void)init;

@end

A: The ambiguity arises (in Swift <= 4.1) because both the class method
+ (void)init;

and NSObjects init method
- (instancetype)init

are called from  Swift as My3rdPartyClass.init(). Possible solutions
are:

*

*Rename the Objective-C class method.

*Annotate the function declaration with a different Swift name:
+(void)init NS_SWIFT_NAME(classInit());

That leaves the Objective-C interface unchanged, but the function can
be called from Swift as
OClass.classInit()

*If no modification of the Objective-C header file is possible then
you can still call the function from Swift as
My3rdPartyClass.init() as Void

The Void return type resolves the ambiguity.
Starting with Swift 4.2 (Xcode 10) you can call the class method as
OClass.`init`()

without any changes in the Objective-C API (attribution goes to
@Hamish).  The backticks tell the compiler that you mean the
member function, not the initializer.


text:
Q: Are generalized symmetric groups maximal finite groups (in a certain sense)? Let $S(m,n)$ be the generalized symmetric group which is a wreath product of the cyclic group of order $m$, denoted here by $\mathbb{Z}_m$, and the symmetric group $S_n$. A standard unitary representation of $S(m,n)$ is given by the semi-direct product of the $n\times n$ permutation matrices and $n \times n$ diagonal matrices with $m$-th roots of unity entries. (These matrices are sometimes called generalized permutation matrices.)
For finite $m$ and $n$ all such unitary matrices form a finite subgroup of $U(n)$ of size $n! m^n$. I'll denote this group of unitary matrices as $M(m,n)$. One way to see that $M(m,n)$ is not a maximal finite subgroup of $U(n)$ is to note that $S(2m,n)$ is a finite group which has $S(m,n)$ as a subgroup. I'm interested in a slightly different question.
Let $U'\in U(n)$ be a unitary matrix which is not in $M(m,n)$ for any $m$ (in other words, $U'$ is not a generalized permutation matrix). Is the group generated by $M(m,n)$ (for some fixed $m$) and $U'$ always infinite?

A: I think the answer is "yes" when $m >6$. By arguments along the lines of Frobenius, Schur and Blichfeldt, if we set $G = \langle M(m,n), U^{\prime} \rangle $ and assume that $G$ is finite, then the non-scalar elements of $G$ whose eigenvalues all lies on an arc of length less than $\frac{\pi}{3}$ on the unit circle generate an Abelian normal subgroup of $G$, say $A$. When $m >6$, this Abelian group has rank $n$, and may be assumed to consist of diagonal matrices. In that case, $C_{G}(A)$ also consists of diagonal matrices (using that $A$ has rank $n$). By Clifford's theorem, we may conclude that the given representation of $A$ is now induced from a $1$-dimensional representation of a subgroup of $G$ of index $n$. In other words, $G$ now consists of monomial matrices.
I suppose, to be more precise, this argument shows that if $m > 6$, any finite unitary overgroup of $M(m,n)$ is conjugate (via a unitary matrix) to a finite group of monomial matrices ( what you call "generalized permutation matrices" are what I am calling monomial matrices).


text:
Q: Polygonize tool error "Process gdal_polygonize.bat failed to start" I am trying to use the Polygonize (Raster to Vector) tool on QGIS-LTR on Windows 11.
When I launch the tool on a layer I get the following error.
Input parameters:
{ 'BAND' : 1, 'EIGHT_CONNECTEDNESS' : False, 'EXTRA' : '', 'FIELD' : 'DN', 'INPUT' : '[LAYERDIRECTORY].tif', 'OUTPUT' : 'TEMPORARY_OUTPUT' }

GDAL command:
gdal_polygonize.bat "[LAYERDIRECTORY].tif" -b 1 -f "GPKG" C:/[…]/OUTPUT.gpkg OUTPUT DN

GDAL command result:
Process gdal_polygonize.bat failed to start. Either gdal_polygonize.bat is missing, or you may have insufficient permissions to run the program
Execution failed after 0.04 seconds

Any clues?


text:
Q: How do I write better template logic with if statements in Django? How can I write this more efficient in Django templates so it won't be a huge if statement? I want to disable an element to ALL pages in request.path and some exceptions for some pages. This is what I got so far
{% if "/create-account/" in request.path or "/lists/" in request.path or "/contact-us/" in request.path or "/news/" in request.path %}
{% else %}
    {% include 'includes/element.html' %}
{% endif %}

There must be a better way. To clarify my needs:
Display this element on all pages except X, Y or Z.

A: The shortest way I can think of at the minute is to include a context variable in the context data for those urls that do need to show it
# views
{ 'ignore_element': ':)' }

# template
{% if not ignore_element %}
    {% include 'includes/element.html' %}
{% endif %}

This would work since its only shown for those that don't include this context value.
Any better solution options would depend on the logic behind why these 4 should be exempt from showing it

A: I would not use the request object directly.
views.py
def contact_us(request):
    my_context = {
        "hide_element_include": True
    }
    return render_to_response('my_template.html',
                      my_context,
                      context_instance=RequestContext(request))

index.html
{% if hide_element_include %}
{% else %}
    {% include 'includes/element.html' %}
{% endif %}

A: Try to keep logic out of the template in most cases. Assuming this page is being served by a Django controller, all you need to do is add a flag for each URL where you want the element to be hidden.
def contact_us(request):
    context = {
        "hide_element": True
    }
    return render('my_template.html', context);

template:
{% if not hide_element %}
    {% include 'includes/element.html' %}
{% endif %}

A: Please consider this easier approach if you have only few pages without "element".
base.html:
{% block some_element %}
  {% include 'includes/element.html' %}
{% endblock %}
{% block content %}
{% endblock %}

pages_with_element.html:
{% extend 'base.html' %}
{% block content %}

content here

{% endblock %}

page_without_element.html:
 {% extend 'base.html' %}
 {% block some_element %}
 {% endblock %}

 {% block content %}

content here

 {% endblock %}


text:
Q: mongoose find document by subdocument's _id Let say I have the following structure:
var Partner = require('../partner/partner.model');

var ContractSchema = new Schema({
      // blahblah
      partners: [Partner.schema]
});

So here every contract has an array of partners, and each partner has an _id property.
I want to search for a contract, which has a partner with a specific _id.
I tried this, but didn't work:
  var ObjectId = require('mongoose').Types.ObjectId;
  Contract.find({
      partners: {
        $elemMatch: {
          _id: {
            $eq: new ObjectId(req.query.partnerId)
          }
        }
      }
    }, function (err, serviceContracts) {
      if (err) {
        return handleError(res, err);
      } else {
        return res.status(200).json(serviceContracts);
      }
    });

EDIT: Here's an example what I have in the db:
{
    "_id" : ObjectId("57e370e72beac9fc21c99ca3"),
    "updatedAt" : ISODate("2016-09-22T05:49:27.000Z"),
    "createdAt" : ISODate("2016-09-22T05:49:27.000Z"),
    "currency" : "USD",
    "partners" : [
        {
            "updatedAt" : ISODate("2016-09-22T05:49:27.000Z"),
            "createdAt" : ISODate("2016-09-22T05:49:27.000Z"),
            "name" : "Apple Inc.",
            "_id" : ObjectId("57e370e72beac9fc21c99caa")
        }
    ],
    "__v" : 0
}

A: As @robertklep said, this is working:
Contract.find({ "partners._id": req.query.partnerId})
  .then(function(contracts) {
    return res.status(200).json(contracts);
  })
  .catch(function(err) {
    return handleError(res, err);
  });


text:
Q: Very long latence only for one of my module Our problem began 02/Sep/2015 17:46 (Paris time), and there is still issus  at present.
We have 2 applications: one for test and development and the other one for the production. The problem is in the production application.

*

*There had been 5 days that we didn't modify the code in production application, but suddenly the latence became very very long the last friday afternoon. The latence was 100~300ms before, but became 30s from from that moment on, and for all requests!

*We use the same code for the test application, but all work well for this application.

*We have several modules in the production application, and there is only one module has this problem, all others mudules work well.

*During the weekend, we make some tests, but still can not find why.
For exemple, the code here:
package app

import (
    "net/http"
)

func init() {
    http.HandleFunc("/", HandlerHeartBeat)
}

func HandlerHeartBeat(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(202)
}

When I deploy this code to the problematic module in the production application, the latence is 2s. Then I try to deploy it to another version in the problematic module, the latence is always very long.
But if deploy this code to other module in the production application (or just create a new module), I get the normal latence(~50ms).

*Our configuration file is very simple:
application: APP_NAME
module: MODULE_NAME
version: 1
runtime: go
api_version: go1

handlers:
- url: /.*
  script: _go_app

I don't know if there is other people meet the same problem like me. Thank you

A: It's very likely there is an issue with Google infrastructure that serve the problematic module.
Probably it calculate some hash code for a module and try to instantiate an instance of the same module on the same machine if possible so app code is cached on the (virtual) machine level if possible. If that machine has issues (for example with hardware) it translates to increased latency for your app.
I would advise:

*

*Deploy code to new module and use it (if possible) while keeping old for troubleshooting.

*Narrow use cases (basic functionality like ping) & raise an issue with Google.