问:
jQuery, move ALL elements lower
I have a serious issue: with jQuery, I have to move ALL elements toward down, because an advertisement banner must be put up there so that it wont cover anything. Its like havin a frameset at the top.
I was trying this:

```<code>jQuery('*').each(function() {
    var $this = jQuery(this);
    if ($this.css('position') === 'fixed' || $this.css('position') === 'absolute')
    {
        $this.css('margin-top', 80);
    }
});
</code>```

but not all element are actually pushed.

答:
Using a combination of your jQuery to add margin to fixed and absolute positioned elements, and padding-top to the body to cover static positioned elements I believe you can cover what you're after.

Notice I changed your selector in the jQuery to look for elements that are not of the 'ad' class.

This assuming your ad is absolutely positioned.

$(':not(.ad)').each(function() {
    var $this = $(this);
    if ($this.css('position') === 'fixed' || $this.css('position') === 'absolute')
    {
        $this.css('margin-top', 80);
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding-top: 80px;
}

.content {
  position: static;
  padding: 0 110px;
}

.ad {
  position: fixed;
  top: 0;
  left: 0;
  width: 728px;
  height: 80px;
  background: red;
}

div.abs {
  width: 100px;
  height: auto;
  position: absolute;
  background: gray;
  top: 0;
  left: 0;
}

div.fxd {
  width: 100px;
  height: auto;
  position: fixed;
  background: gray;
  top: 0;
  right: 0;
}</code>```

Content in a static positioned block level div. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam venenatis elit nunc, a bibendum nisi volutpat id. Morbi pretium ultrices tortor sed porta. Praesent ullamcorper tristique luctus. Suspendisse sodales, est gravida accumsan sodales, urna turpis congue tortor, in ullamcorper justo magna et ex. Aliquam commodo, mi eget euismod volutpat, lorem lectus ultricies est, at congue velit ipsum vitae neque. Aenean consectetur ante lacus, ac iaculis sapien pulvinar a. Aenean porta porttitor faucibus. Sed nec metus vel enim suscipit placerat. Phasellus cursus pretium ex at venenatis.

Content in a static positioned block level div. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam venenatis elit nunc, a bibendum nisi volutpat id. Morbi pretium ultrices tortor sed porta. Praesent ullamcorper tristique luctus. Suspendisse sodales, est gravida accumsan sodales, urna turpis congue tortor, in ullamcorper justo magna et ex. Aliquam commodo, mi eget euismod volutpat, lorem lectus ultricies est, at congue velit ipsum vitae neque. Aenean consectetur ante lacus, ac iaculis sapien pulvinar a. Aenean porta porttitor faucibus. Sed nec metus vel enim suscipit placerat. Phasellus cursus pretium ex at venenatis.

This is a absolute positioned div at 0/0

This is a fixed positioned div at 0/0

```

Title: jQuery, move ALL elements lower

Body:
I have a serious issue: with jQuery, I have to move ALL elements toward down, because an advertisement banner must be put up there so that it wont cover anything. Its like havin a frameset at the top.
I was trying this:

jQuery('*').each(function() {
    var $this = jQuery(this);
    if ($this.css('position') === 'fixed' || $this.css('position') === 'absolute')
    {
        $this.css('margin-top', 80);
    }
});

but not all element are actually pushed.

Body:
Using a combination of your jQuery to add margin to fixed and absolute positioned elements, and padding-top to the body to cover static positioned elements I believe you can cover what you're after.

Notice I changed your selector in the jQuery to look for elements that are not of the 'ad' class.

This assuming your ad is absolutely positioned.

$(':not(.ad)').each(function() {
    var $this = $(this);
    if ($this.css('position') === 'fixed' || $this.css('position') === 'absolute')
    {
        $this.css('margin-top', 80);
    }
});

body {
  padding-top: 80px;
}

.content {
  position: static;
  padding: 0 110px;
}

.ad {
  position: fixed;
  top: 0;
  left: 0;
  width: 728px;
  height: 80px;
  background: red;
}

div.abs {
  width: 100px;
  height: auto;
  position: absolute;
  background: gray;
  top: 0;
  left: 0;
}

div.fxd {
  width: 100px;
  height: auto;
  position: fixed;
  background: gray;
  top: 0;
  right: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<p>Content in a static positioned block level div. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam venenatis elit nunc, a bibendum nisi volutpat id. Morbi pretium ultrices tortor sed porta. Praesent ullamcorper tristique luctus. Suspendisse sodales, est gravida accumsan sodales, urna turpis congue tortor, in ullamcorper justo magna et ex. Aliquam commodo, mi eget euismod volutpat, lorem lectus ultricies est, at congue velit ipsum vitae neque. Aenean consectetur ante lacus, ac iaculis sapien pulvinar a. Aenean porta porttitor faucibus. Sed nec metus vel enim suscipit placerat. Phasellus cursus pretium ex at venenatis.</p>
</div>

<div class="content">
<p>Content in a static positioned block level div. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam venenatis elit nunc, a bibendum nisi volutpat id. Morbi pretium ultrices tortor sed porta. Praesent ullamcorper tristique luctus. Suspendisse sodales, est gravida accumsan sodales, urna turpis congue tortor, in ullamcorper justo magna et ex. Aliquam commodo, mi eget euismod volutpat, lorem lectus ultricies est, at congue velit ipsum vitae neque. Aenean consectetur ante lacus, ac iaculis sapien pulvinar a. Aenean porta porttitor faucibus. Sed nec metus vel enim suscipit placerat. Phasellus cursus pretium ex at venenatis.</p>
</div>

<div class="abs">This is a <strong>absolute</strong> positioned div at 0/0</div>
<div class="fxd">This is a <strong>fixed</strong> positioned div at 0/0</div>

<div class="ad"></div>


来源: stackexchange

问:
PHP how to check if IP RANGE provided is IPv4 or IPv6
So I have the following two IP ranges

```<code>2a02:c78::/29
2.120.0.0/13
</code>```

What php function can i use to tell the difference between a ipv4 range and a ipv6 range

Need something like this

```<code>function ip_range_type($range_ip)
{
//if ip range provided is ipv4 then

//if ip range provided is ipv6 then
}
</code>```

答:
Credit for this solution goes to user @deceze</p>

```<code>function ip_range_type($range_ip)
{
    if (strpos($range_ip, ':') !== false) {
        //if ip range provided is ipv6 then
        echo "range provided is ipv6";
    } else {
        //if ip range provided is ipv4 then
        echo "range provided is ipv4";
    }
}
$range_ip = "2a02:c78::/29";
ip_range_type($range_ip);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have the following two IP ranges

2a02:c78::/29
2.120.0.0/13

What php function can i use to tell the difference between a ipv4 range and a ipv6 range

Need something like this

function ip_range_type($range_ip)
{
//if ip range provided is ipv4 then

//if ip range provided is ipv6 then
}

Body:
Credit for this solution goes to user @deceze

function ip_range_type($range_ip)
{
    if (strpos($range_ip, ':') !== false) {
        //if ip range provided is ipv6 then
        echo "range provided is ipv6";
    } else {
        //if ip range provided is ipv4 then
        echo "range provided is ipv4";
    }
}
$range_ip = "2a02:c78::/29";
ip_range_type($range_ip);


问:
Showing a TYPE_SYSTEM_ALERT (Window type can not be changed after the window is added.)
I want to show an alert window to ask a question to user. I am using the code given below. I get the following error:

Window type can not be changed after the window is added.

```<code>try {
    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                PixelFormat.TRANSLUCENT);

    WindowManager wm = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

    ViewGroup mTopView = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_subscription_buy, null);
    getWindow().setAttributes(params);
    wm.addView(mTopView, params);

} catch (Exception ex) {
    ex.printStackTrace();
}
</code>```

How can I fix it or is there any solution to ask a question to user on top of all activities?

Note: I granted user with this Manifest permission rule:

```<code>    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
</code>```

答: Enes, possibly this is the reason</p>

Body:
I want to show an alert window to ask a question to user. I am using the code given below. I get the following error:

Window type can not be changed after the window is added.

try {
    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                PixelFormat.TRANSLUCENT);

    WindowManager wm = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

    ViewGroup mTopView = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_subscription_buy, null);
    getWindow().setAttributes(params);
    wm.addView(mTopView, params);

} catch (Exception ex) {
    ex.printStackTrace();
}

How can I fix it or is there any solution to ask a question to user on top of all activities?

Note: I granted user with this Manifest permission rule:

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

Body: Enes, possibly this is the reason


问:
How can I do for loop with long value
I need to do codes with for loop and long value like this:

```<code>for(long i=1;i<lines.length; i++){

    char tmp = lines[i].charAt(lines[i].length()-1);

    int index = lines[i].lastIndexOf(" ");

    lines[i] = lines[i].substring(0, index);

    if(tmp != lastChar)
        lines[i] = "S" + lines[i];
    else
        lines[i]=" "+lines[i];

    lastChar = tmp;
}
</code>```

The problem is: incompatible  types:possible lossy conversion from long to int I don't know how to fix it

答:
you are using long in for loop that is correct but when you are using index in lines[i] then problem start. java says index is always int but in your case it is long.

and long can not cast directly into int.either change long data type to int data type in for loop or  cast i variable when you are using as index like lines[(int)i](not prefer).

Title: How can I do for loop with long value

Body:
I need to do codes with for loop and long value like this:

for(long i=1;i<lines.length; i++){

    char tmp = lines[i].charAt(lines[i].length()-1);

    int index = lines[i].lastIndexOf(" ");

    lines[i] = lines[i].substring(0, index);

    if(tmp != lastChar)
        lines[i] = "S" + lines[i];
    else
        lines[i]=" "+lines[i];

    lastChar = tmp;
}

The problem is: incompatible  types:possible lossy conversion from long to int I don't know how to fix it


问:
How do I make an attributed string using Swift?
I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The "g" symbol for grams needs to be attached to my UILabel that I am using to display the amount. The numbers in the UILabel are changing dynamically with user input just fine, but I need to add a lower case "g" on the end of the string that is formatted differently from the  updating numbers. The "g" needs to be attached to the numbers so that as the number size and position changes, the "g" "moves" with the numbers. I'm sure this problem has been solved before so a link in the right direction would be helpful as I've googled my little heart out.

I've searched through the documentation for an attributed string and I even downloded an "Attributed String Creator" from the app store, but the resulting code is in Objective-C and I am using Swift. What would be awesome, and probably helpful to other developers learning this language, is a clear example of creating a custom font with custom attributes using an attributed string in Swift. The documentation for this is very confusing as there is not a very clear path on how to do so. My plan is to create the attributed string and add it to the end of my coffeeAmount string.

```<code>var coffeeAmount: String = calculatedCoffee + attributedText
</code>```

Where calculatedCoffee is an Int converted to a string and "attributedText" is the lowercase "g" with customized font that I am trying to create. Maybe I'm going about this the wrong way. Any help is appreciated!

答:
I created an online tool that is going to solve your problem! You can write your string and apply styles graphically and the tool gives you objective-c and swift code to generate that string.

Also is open source so feel free to extend it and send PRs.

Transformer Tool

Github

Body:
I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The "g" symbol for grams needs to be attached to my UILabel that I am using to display the amount. The numbers in the UILabel are changing dynamically with user input just fine, but I need to add a lower case "g" on the end of the string that is formatted differently from the  updating numbers. The "g" needs to be attached to the numbers so that as the number size and position changes, the "g" "moves" with the numbers. I'm sure this problem has been solved before so a link in the right direction would be helpful as I've googled my little heart out.

I've searched through the documentation for an attributed string and I even downloded an "Attributed String Creator" from the app store, but the resulting code is in Objective-C and I am using Swift. What would be awesome, and probably helpful to other developers learning this language, is a clear example of creating a custom font with custom attributes using an attributed string in Swift. The documentation for this is very confusing as there is not a very clear path on how to do so. My plan is to create the attributed string and add it to the end of my coffeeAmount string.

var coffeeAmount: String = calculatedCoffee + attributedText

Where calculatedCoffee is an Int converted to a string and "attributedText" is the lowercase "g" with customized font that I am trying to create. Maybe I'm going about this the wrong way. Any help is appreciated!


问:
webSocketServer node.js how to differentiate clients
I am trying to use sockets with node.js, I succeded but I don't know how to differentiate clients in my code.
The part concerning sockets is this:

```<code>var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        console.log('received: %s', message);
        ws.send(message);
    });
    ws.send('something');
});
</code>```

This code works fine with my client js.

But I would like to send a message to a particular user or all users having sockets open on my server.

In my case I send a message as a client and I receive a response but the others user show nothing.

I would like for example user1 sends a message to the server via webSocket and I send a notification to user2 who has his socket open.

答:
One possible solution here could be appending the deviceId in front of the user id, so we get to separate multiple users with same user id but on different devices.

ws://xxxxxxx:9000/userID/<<deviceId>>

Body:
I am trying to use sockets with node.js, I succeded but I don't know how to differentiate clients in my code.
The part concerning sockets is this:

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        console.log('received: %s', message);
        ws.send(message);
    });
    ws.send('something');
});

This code works fine with my client js.

But I would like to send a message to a particular user or all users having sockets open on my server.

In my case I send a message as a client and I receive a response but the others user show nothing.

I would like for example user1 sends a message to the server via webSocket and I send a notification to user2 who has his socket open.


问:
Can't convert object of type java.lang.Long to type
I'm trying to connect my app to a Firebase Database, but whenever I launch the code that problem show up

that's my main activity

```<code>public class MainActivity extends AppCompatActivity {

    private static final String TAG = "ViewDatabase";

    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference("Discount/Business");

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                UserInformation uInfo = new UserInformation();
                uInfo.setAltro(ds.child("Altro").getValue(UserInformation.class).getAltro());
                uInfo.setCognome(ds.child("Cognome").getValue(UserInformation.class).getCognome());
                uInfo.setInformazioni(ds.child("Informazioni").getValue(UserInformation.class).getInformazioni());
                uInfo.setNome(ds.child("Nome").getValue(UserInformation.class).getNome());

                Log.d(TAG, "showData: Altro: " + uInfo.getAltro());
                Log.d(TAG, "showData: Cognome: " + uInfo.getCognome());
                Log.d(TAG, "showData: Informazioni: " + uInfo.getInformazioni());
                Log.d(TAG, "showData: Nome: " + uInfo.getNome());

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
</code>```

that's my User class

```<code>public class UserInformation {
private String Altro;
private String Cognome;
private String Informazioni;
private String Nome;

public UserInformation(){

}

public String getAltro() {
    return Altro;
}

public void setAltro(String altro) {
    Altro = altro;
}

public String getCognome() {
    return Cognome;
}

public void setCognome(String cognome) {
    Cognome = cognome;
}

public String getInformazioni() {
    return Informazioni;
}

public void setInformazioni(String informazioni) {
    Informazioni = informazioni;
}

public String getNome() {
    return Nome;
}

public void setNome(String nome) {
    Nome = nome;
}
</code>```

My firebase database

and my log error

```<code>11-14 10:59:55.016 2909-2909/com.app8 E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.app8, PID: 2909
                                                        com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.app8.UserInformation
                                                            at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
                                                            at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                                                            at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                                                            at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                            at com.app8.MainActivity$1.onDataChange(MainActivity.java:41)
                                                            at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
                                                            at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                                                            at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

It's my first time using Firebase, I've seen other questions related to the topic but I can't figure out how to make it works, I hope you can help me.

thanks for your help, any suggestion is highly appreciated

答:
Can you try below.

UserInformation uiFromSnapShot = ds.getValue(UserInformation.class);
uInfo.setXXX(uiFromSnapShot.getXXX);

Body:
I'm trying to connect my app to a Firebase Database, but whenever I launch the code that problem show up

that's my main activity

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "ViewDatabase";

    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference("Discount/Business");

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                UserInformation uInfo = new UserInformation();
                uInfo.setAltro(ds.child("Altro").getValue(UserInformation.class).getAltro());
                uInfo.setCognome(ds.child("Cognome").getValue(UserInformation.class).getCognome());
                uInfo.setInformazioni(ds.child("Informazioni").getValue(UserInformation.class).getInformazioni());
                uInfo.setNome(ds.child("Nome").getValue(UserInformation.class).getNome());

                Log.d(TAG, "showData: Altro: " + uInfo.getAltro());
                Log.d(TAG, "showData: Cognome: " + uInfo.getCognome());
                Log.d(TAG, "showData: Informazioni: " + uInfo.getInformazioni());
                Log.d(TAG, "showData: Nome: " + uInfo.getNome());

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

that's my User class

public class UserInformation {
private String Altro;
private String Cognome;
private String Informazioni;
private String Nome;

public UserInformation(){

}

public String getAltro() {
    return Altro;
}

public void setAltro(String altro) {
    Altro = altro;
}

public String getCognome() {
    return Cognome;
}

public void setCognome(String cognome) {
    Cognome = cognome;
}

public String getInformazioni() {
    return Informazioni;
}

public void setInformazioni(String informazioni) {
    Informazioni = informazioni;
}

public String getNome() {
    return Nome;
}

public void setNome(String nome) {
    Nome = nome;
}

My firebase database

and my log error

11-14 10:59:55.016 2909-2909/com.app8 E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.app8, PID: 2909
                                                        com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.app8.UserInformation
                                                            at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
                                                            at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                                                            at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                                                            at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                            at com.app8.MainActivity$1.onDataChange(MainActivity.java:41)
                                                            at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
                                                            at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                                                            at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

It's my first time using Firebase, I've seen other questions related to the topic but I can't figure out how to make it works, I hope you can help me.

thanks for your help, any suggestion is highly appreciated


问:
Application fails when dll added to GAC, okay otherwise
I have an application which references some .Net dlls and is used to convert a file between different formats. If I add a reference to the .dll file, my application runs without problem.

However, if I add the dll to the GAC, and reference it from there, my application fails during run time, due to a parsing error. The physical location of the dlls are unchanged.

I have several configuration files which are accessed via environment variables, and these are used to parse input files.

Any ideas what might be the problem?

```<code>    private static string FILE_CONFIGURATION = "configuration.xml";

    string configurationPath = "c:\\temp\\CDXMLViewerDist\\" + FILE_CONFIGURATION;
    System.Environment.SetEnvironmentVariable(translator.domains.XMLDomainConfiguration.FILE_CONFIGURATION_PATH, configurationPath);
    System.Environment.SetEnvironmentVariable(translator.domains.XMLDomainConfiguration.DOMAIN_CONFIGURATION_PROPERTY_KEY, typeof(XMLDomainConfiguration).FullName);

String strPath = "C:\\temp\\out.cdxml";

CDXMLReader reader = new CDXMLReader();
reader.Read(strPath);  // Runs fine if reference dll as file, throws exception if via GAC
</code>```

答:
The problem was due to an attempt to instantiate an object using

object o = Activator.CreateInstance(assemblyName, fullyQualifiedTypeName);

When accessing via the GAC, I needed to use a fully qualified assembly name rather than just the assembly name e.g.

"AssemblyName, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=abcdef1234567890"

ContentLicense: CC BY-SA 2.5

Body:
I have an application which references some .Net dlls and is used to convert a file between different formats. If I add a reference to the .dll file, my application runs without problem.

However, if I add the dll to the GAC, and reference it from there, my application fails during run time, due to a parsing error. The physical location of the dlls are unchanged.

I have several configuration files which are accessed via environment variables, and these are used to parse input files.

Any ideas what might be the problem?

    private static string FILE_CONFIGURATION = "configuration.xml";

    string configurationPath = "c:\\temp\\CDXMLViewerDist\\" + FILE_CONFIGURATION;
    System.Environment.SetEnvironmentVariable(translator.domains.XMLDomainConfiguration.FILE_CONFIGURATION_PATH, configurationPath);
    System.Environment.SetEnvironmentVariable(translator.domains.XMLDomainConfiguration.DOMAIN_CONFIGURATION_PROPERTY_KEY, typeof(XMLDomainConfiguration).FullName);

String strPath = "C:\\temp\\out.cdxml";

CDXMLReader reader = new CDXMLReader();
reader.Read(strPath);  // Runs fine if reference dll as file, throws exception if via GAC


问:
Why does Powershell's Format-List * not output all properties
When I do a ... | Format-List one of the properties is Path.

When I do a ... | Format-List * the Path property is missing.

Why?

```<code>[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List

Name        :
CommandType : Script
Definition  : $MyInvocation.MyCommand | Format-List
Path        :

[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List *

HelpUri            :
ScriptBlock        : $MyInvocation.MyCommand | Format-List *
Definition         : $MyInvocation.MyCommand | Format-List *
OutputType         : {}
Name               :
CommandType        : Script
Visibility         : Public
ModuleName         :
Module             :
RemotingCapability : PowerShell
Parameters         :
ParameterSets      : {}
</code>```

答:
When running in the console, the Path property doesn't actually exist. Format-List - without * - is using a template to determine which properties to display. Unfortunately I can't find documentation links to explain this further, and how this can be configured - will edit if I do.

See Matt's answer

You can see this by running $MyInvocation.MyCommand | Get-Member and noting that Path is not one of the properties. Makes sense, as you are running the command in the console, not from a script.

In  a script, both $MyInvocation.MyCommand | Format-List and $MyInvocation.MyCommand | Format-List * include Path

$MyInvocation is populated only for scripts, function, and script blocks.

From about_Automatic_Variables. Looks like PowerShell is treating your command as a script in order for $MyInvocation to be (partly) populated.

Body:
When I do a ... | Format-List one of the properties is Path.

When I do a ... | Format-List * the Path property is missing.

Why?

[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List

Name        :
CommandType : Script
Definition  : $MyInvocation.MyCommand | Format-List
Path        :

[DBG]: PS C:\Directory>> $MyInvocation.MyCommand | Format-List *

HelpUri            :
ScriptBlock        : $MyInvocation.MyCommand | Format-List *
Definition         : $MyInvocation.MyCommand | Format-List *
OutputType         : {}
Name               :
CommandType        : Script
Visibility         : Public
ModuleName         :
Module             :
RemotingCapability : PowerShell
Parameters         :
ParameterSets      : {}


问:
How Softlayer API set OR condition in object filer
For example, I want ot GET https://api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/46/getItems.json with some specified categories. I tried to use String contains filters in https://sldn.softlayer.com/article/object-filters, operation = '*= guest_core ram port_speed'.

```<code>Request URL:  GET https://api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/46/getItems.json?objectFilter=%7B%22items%22%3A%7B%22categories%22%3A%7B%22categoryCode%22%3A%7B%22operation%22%3A%22%2A%3D+guest_core+ram+port_speed%22%7D%7D%7D%7D&objectMask=mask%5Bdescription%2C+capacity%2C+prices%5Bid%2C+locationGroupId%2C+categories%5BcategoryCode%5D%5D%5D
</code>```

But it returned empty result.

答: The objectFilter does not provide support for "OR" operation</p>

Body:
For example, I want ot GET https://api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/46/getItems.json with some specified categories. I tried to use String contains filters in https://sldn.softlayer.com/article/object-filters, operation = '*= guest_core ram port_speed'.

Request URL:  GET https://api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/46/getItems.json?objectFilter=%7B%22items%22%3A%7B%22categories%22%3A%7B%22categoryCode%22%3A%7B%22operation%22%3A%22%2A%3D+guest_core+ram+port_speed%22%7D%7D%7D%7D&objectMask=mask%5Bdescription%2C+capacity%2C+prices%5Bid%2C+locationGroupId%2C+categories%5BcategoryCode%5D%5D%5D

But it returned empty result.


问:
can some one help me calculating time difference between two Date Stamps?
My date formats are like this:
(u'Task', u'2017-01-06T02:23:44.000-0500') .. stage 1
(u'Task', u'2017-01-06T05:27:10.000-0500') .. stage 2
(u'Task', u'2017-01-10T14:42:44.000-0500') ...stage 2

I have to calulcate the time difference between every stage
I am using this (which I know is incorrect :-()

```<code>    import datetime as dt
    date_format = "yyyy-mm-ddThh-mm-ss"
    x1= d1.split('T')[0]+' '+(d1.split('T'))[1][:8]
    x2= d2.split('T')[0]+' '+(d2.split('T'))[1][:8]

    d1=('2017-01-06T02:23:44.000-0500')
    d2=('2017-01-19T17:30:21.000-0500')

#some string slicing to get rid of T and the timezone indicator
    start_dt = dt.datetime.strptime(x1, 'yyyy-mm-ddhh:mm:ss')
    end_dt = dt.datetime.strptime(x2, 'yyyy-mm-ddhh:mm:ss')

    x = start_dt - end_dt
</code>```

It returns me a format mismatch error

can someone help me find the time spent between stage 1 and stage 2 I have to calculate this recursively

答:
Your format string should be '%Y-%m-%d%H%M%S'.
So:

```<code>start_dt = dt.datetime.strptime((d1.split('T')[0]+''+(d1.split('T'))[1][:8]), '%Y-%m-%d%H:%M:%S')
end_dt = dt.datetime.strptime((d2.split('T')[0]+''+(d2.split('T'))[1][:8]), '%Y-%m-%d%H:%M:%S')
</code>```

Body:
My date formats are like this:
(u'Task', u'2017-01-06T02:23:44.000-0500') .. stage 1
(u'Task', u'2017-01-06T05:27:10.000-0500') .. stage 2
(u'Task', u'2017-01-10T14:42:44.000-0500') ...stage 2

I have to calulcate the time difference between every stage
I am using this (which I know is incorrect :-()

    import datetime as dt
    date_format = "yyyy-mm-ddThh-mm-ss"
    x1= d1.split('T')[0]+' '+(d1.split('T'))[1][:8]
    x2= d2.split('T')[0]+' '+(d2.split('T'))[1][:8]

    d1=('2017-01-06T02:23:44.000-0500')
    d2=('2017-01-19T17:30:21.000-0500')

#some string slicing to get rid of T and the timezone indicator
    start_dt = dt.datetime.strptime(x1, 'yyyy-mm-ddhh:mm:ss')
    end_dt = dt.datetime.strptime(x2, 'yyyy-mm-ddhh:mm:ss')

    x = start_dt - end_dt

It returns me a format mismatch error

can someone help me find the time spent between stage 1 and stage 2 I have to calculate this recursively

Body:
Your format string should be '%Y-%m-%d%H%M%S'.
So:

start_dt = dt.datetime.strptime((d1.split('T')[0]+''+(d1.split('T'))[1][:8]), '%Y-%m-%d%H:%M:%S')
end_dt = dt.datetime.strptime((d2.split('T')[0]+''+(d2.split('T'))[1][:8]), '%Y-%m-%d%H:%M:%S')


问:
Extract date from string - react native
Currently, I am working on receipt scanning app. I need a date from an extracted text:

So the date format is fixed. So how can I use regx to extract date?

答:
A simple RegEx to capture the dates in this format would be

```<code>/\s\d\d\/\d\d\/\d\d\s/
</code>```

and then use String.prototype.trim() to trim away leading and trailing whitespaces.

Using:

```<code>/\s[0123]\d\/[01]\d\/\d\d\s/
</code>```

provides a little more validation, removing invalid months and days.

Title: Extract date from string - react native

Body:
A simple RegEx to capture the dates in this format would be

/\s\d\d\/\d\d\/\d\d\s/

and then use String.prototype.trim() to trim away leading and trailing whitespaces.

Using:

/\s[0123]\d\/[01]\d\/\d\d\s/

provides a little more validation, removing invalid months and days.


问:
What is the best software to host a ruby on rails application on production?
Is webrick the only good option?
I know there is a way of using apache, but is it better than webrick?</p>

答:
As stated before: Webrick is for development only, do not use that for deploying.

The simplest replacement for Webrick is using mongrel. But that doesn't scale well (in the end). A mongrel is a single thread, so a mongrel-process can only handle one process at a time. If you have a lot of users, you will have to install many mongrel, load-balanced by an apache or nginx in front of it.

Then it depends on your server platform: on any linux flavor (ubuntu/debian/mac os) you could use apache/nginx in front of passenger, mongrel, thin, unicorn, ...

From all these options, passenger has the easiest integration.
If you use mongrel/thin/unicorn you will have to specify your own load-balancing between different instances and manage that yourself. Passenger handles that for you.

If you are on Windows passenger can't be used, but mongrel or thin are still viable (not unicorn). On Windows i would recommend using mongrel_service for each mongrel-instace you keep running, behind an apache webserver.

But heroku is the easiest of them all (if you do not have to deploy on a server inside your building).


问:
Calculate radius distance using cos/sin including if/then and inner join
What i need:

I need to write some kind of IF statement inside query to pick different coordinates, if table1.business_id is equal to 1.

For example:

Pick lng and lat fields from table1 if table1.business_id = 1, else, pick lng and lat fields from table2.

Query:

```<code>SELECT *,
(3959 * acos(
   cos(radians('.$cords['result']['latitude'].')) *
   cos(radians(lat)) * cos( radians(lng) -
   radians('.$cords['result']['longitude'].')) +
   sin(radians('.$cords['result']['latitude'].')) *
   sin(radians(lat))
)) AS distance
   FROM table1 INNER JOIN table2 ON table2.id = table1.business_id
   WHERE type <> "industry" AND '.$query.'
   HAVING distance < '.$radius.'
   ORDER BY distance LIMIT 100
</code>```

How i can get this working? How to write technically correct query?

Thanks for any answers.

答:
'You can use case when </p>

```<code>select a, b,
case
  when table1.business_id = 1
  then 'Pick lng and lat fields from table1'
  else 'pick lng and lat fields from table2'
end col1, clo2
from table1, table 2 where table1.id = table2.id
</code>```

Body:
What i need:

I need to write some kind of IF statement inside query to pick different coordinates, if table1.business_id is equal to 1.

For example:

Pick lng and lat fields from table1 if table1.business_id = 1, else, pick lng and lat fields from table2.

Query:

SELECT *,
(3959 * acos(
   cos(radians('.$cords['result']['latitude'].')) *
   cos(radians(lat)) * cos( radians(lng) -
   radians('.$cords['result']['longitude'].')) +
   sin(radians('.$cords['result']['latitude'].')) *
   sin(radians(lat))
)) AS distance
   FROM table1 INNER JOIN table2 ON table2.id = table1.business_id
   WHERE type <> "industry" AND '.$query.'
   HAVING distance < '.$radius.'
   ORDER BY distance LIMIT 100

How i can get this working? How to write technically correct query?

Thanks for any answers.

Body:
'You can use case when

select a, b,
case
  when table1.business_id = 1
  then 'Pick lng and lat fields from table1'
  else 'pick lng and lat fields from table2'
end col1, clo2
from table1, table 2 where table1.id = table2.id


问:
How can I configure my AngularJS 5.0.1 application to load my scripts only when the html is loaded?
I'm starting my first AngularJS 5.0.1 application using this theme: https://themeforest.net/item/ubold-responsive-web-app-kit/13489470

But I'm having some problems... The .js files required for the theme that I've put on angular-cli.json are loaded before the HTML, so the script can't find the elements to apply the necessary events to the theme. I need firstly load the HTML, and only after that, load de .js files. Someone could help me, please?

答:
I used to do that on AngularJS by adding a $timeout around ~150ms and then load the functions I need.

Hope it's useful for you.


问:
Script suddenly not working at Canvas
In Unity I added simple button...and I have simple following code

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System;

public class Test : MonoBehaviour
{
    public Button mk;

    void Start ()
    {
        mk.onClick.AddListener(asd);
    }

    void asd()
    {
        print(" asd");
    }
}
```

I added this script into canvas...this was working fine..but after restarting suddenly it is not working at all...I also tried add another script and this not working.. I think something wrong happened to this canvas.Antoher canvas works fine.

答:
It can be because, you doesn't have EventSystem in your scene. Even if you have it, try to delete and add it again. It solved my problem once.

EventSystem

Title: Script suddenly not working at Canvas

Body:
In Unity I added simple button...and I have simple following code

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System;

public class Test : MonoBehaviour
{
    public Button mk;

    void Start ()
    {
        mk.onClick.AddListener(asd);
    }

    void asd()
    {
        print(" asd");
    }
}

I added this script into canvas...this was working fine..but after restarting suddenly it is not working at all...I also tried add another script and this not working.. I think something wrong happened to this canvas.Antoher canvas works fine.


问:
How to extract column wise data from pdf in powershell?
I want to read a .pdf file which has some data. How can I extract complete data from one specific column only using powershell? I am using iText 5 .NET (aka iTextSharp) for pdf data extraction.

This is my current code, which extracts an entire line:

```<code>$reader = New-Object iTextSharp.text.pdf.pdfreader -ArgumentList testPOC.pdf
$page = 2
$text = [iTextSharp.text.pdf.parser.PdfTextExtractor]::GetTextFromPage($reader, $page).Split([char]0x000A)
Write-Host $text[5]
</code>```

Output is shown as:

```
ID          Working Agent   Assistant Name        Plan           Gender  Year   Amount     Comm.%  Split%   Commission
4169985061  Paul E. Ted     Alskd, Ols      fhghslhshsl+(0sdhsk)    M      12   $1,234.00   0.45%   100.00%  $32.78
```

How can I get data only from one single column (eg. only from salary column)?

答:
This is just a blind stab at the answer, because we don't know what type of data $text is (unless we are iTextSharp experts).  You could find that out for us by entering:

```<code>$text.gettype()
</code>```

From the way it shows up on output, it almost appears that it's a PSCustomObject.  If so, an approach like this might work:

```<code>$text | select-object ID, Commission
</code>```

I used Commission because I couldn't see Salary in your output.  I added ID for the sake of context.

Note:  a real answer is going to have to wait for somebody who uses iTextSharp and might know the datatype of $text without being told.  That could be a long wait.

Body:
I want to read a .pdf file which has some data. How can I extract complete data from one specific column only using powershell? I am using iText 5 .NET (aka iTextSharp) for pdf data extraction.

This is my current code, which extracts an entire line:

$reader = New-Object iTextSharp.text.pdf.pdfreader -ArgumentList testPOC.pdf
$page = 2
$text = [iTextSharp.text.pdf.parser.PdfTextExtractor]::GetTextFromPage($reader, $page).Split([char]0x000A)
Write-Host $text[5]

Output is shown as:

ID          Working Agent   Assistant Name        Plan           Gender  Year   Amount     Comm.%  Split%   Commission
4169985061  Paul E. Ted     Alskd, Ols      fhghslhshsl+(0sdhsk)    M      12   $1,234.00   0.45%   100.00%  $32.78

How can I get data only from one single column (eg. only from salary column)?

Body:
This is just a blind stab at the answer, because we don't know what type of data $text is (unless we are iTextSharp experts).  You could find that out for us by entering:

$text.gettype()

From the way it shows up on output, it almost appears that it's a PSCustomObject.  If so, an approach like this might work:

$text | select-object ID, Commission

I used Commission because I couldn't see Salary in your output.  I added ID for the sake of context.

Note:  a real answer is going to have to wait for somebody who uses iTextSharp and might know the datatype of $text without being told.  That could be a long wait.


问:
Testing multidomain Rails 3 app with Capybara
I want to test my multidomain RoR3 App.

Here's my test_helper.rb

```<code>ENV["RAILS_ENV"] = "test"

require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'capybara/rails'
require 'blueprints'

class ActiveSupport::TestCase

end

class ActionDispatch::IntegrationTest
  include Capybara

  def host
    "http://#{subdomain}.lvh.me:3000"
  end

  def subdomain
    @subdomain ? @subdomain : 'demostore'
  end

  def visit(url)
    super("http://#{subdomain}.lvh.me:3000#{url}")
  end
end
</code>```

And my integration test:

```<code>require 'test_helper'

class ProductsTest < ActionDispatch::IntegrationTest

  def setup
    @subdomain = 'demostore'
    # creating stuff
  end

  def teardown
    # deleting stuff
  end

  test "user views product list" do
    visit('/')
    assert page.has_css?('ul.product-listing')
    assert page.has_xpath?("//ul[@class='product-listing']/li", :count => 12)
  end

  test "user views product page" do
    product = Product.first

    visit('/')
    find(:xpath, "//ul[@class='product-listing']/li/a[1]").click
    save_and_open_page
  end

end
</code>```

And I'm sure the link exists. There is problem with clicking and filling stuff.

```<code>click_link('Existent link title')
</code>```

doesn't work too.

I think the default Capybara's driver Rack::Test could have problems with this multidomain stuff?

答:
In your setup, call this rack::test function, which will change your host's value. Well, it changes the host that gets returned about the fake web request.</p>

```<code>host! "#{store.subdomain}.example.com"
</code>```

Body:
I want to test my multidomain RoR3 App.

Here's my test_helper.rb

ENV["RAILS_ENV"] = "test"

require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'capybara/rails'
require 'blueprints'

class ActiveSupport::TestCase

end

class ActionDispatch::IntegrationTest
  include Capybara

  def host
    "http://#{subdomain}.lvh.me:3000"
  end

  def subdomain
    @subdomain ? @subdomain : 'demostore'
  end

  def visit(url)
    super("http://#{subdomain}.lvh.me:3000#{url}")
  end
end

And my integration test:

require 'test_helper'

class ProductsTest < ActionDispatch::IntegrationTest

  def setup
    @subdomain = 'demostore'
    # creating stuff
  end

  def teardown
    # deleting stuff
  end

  test "user views product list" do
    visit('/')
    assert page.has_css?('ul.product-listing')
    assert page.has_xpath?("//ul[@class='product-listing']/li", :count => 12)
  end

  test "user views product page" do
    product = Product.first

    visit('/')
    find(:xpath, "//ul[@class='product-listing']/li/a[1]").click
    save_and_open_page
  end

end

And I'm sure the link exists. There is problem with clicking and filling stuff.

click_link('Existent link title')

doesn't work too.

I think the default Capybara's driver Rack::Test could have problems with this multidomain stuff?

Body:
In your setup, call this rack::test function, which will change your host's value. Well, it changes the host that gets returned about the fake web request.

host! "#{store.subdomain}.example.com"


问:
How distribute OSX cli / server app
Im building a cli app that can run in server mode for osx in golang. I come from the server world and have no idea how properly distribute a consumer cli tool for osx. The cli can run as a service which can be easily achieved with launchd.

Launchd config:

```<code><plist version="1.0">
    <dict>
        <key>KeepAlive</key>
        <true/>
        <key>Label</key>
        <string>focus-daemon</string>
        <key>RunAtLoad</key>
        <true />
        <key>Program</key>
        <string>/usr/local/bin/focus</string>
  </dict>
</plist>
</code>```

Building and running is also quite simple:

```<code>go build main.go
sudo cp main /usr/local/bin/focus
rm main
sudo chown root /usr/local/bin/focus
sudo chmod 4555 /usr/local/bin/focus
cp focus.plist ~/Library/LaunchAgents/com.21stio.focus.plist
launchctl load ~/Library/LaunchAgents/com.21stio.focus.plist
</code>```

When being build the process requires sudo to set a sbit on the binary.

I don't want the user having to run a .sh script. Maybe I could use brew and/or a DMG for that. But I have no idea how I can put the Launchd config at the right spot then.

答:
As was suggested in the comments, installer pkgs are usually the way to go with this type of software. You're probably familiar with them if you've manually installed device drivers, OS updates and other lower-level software on the Mac.

You can also generate them with command-line utilities, and don't necessarily need to use the 3rd party app that pvg suggested in the comment. This answer is a good starting point. Using the command-line tools also lets you automate package building as part of your standard build process.

Note that Apple's own old "PackageMaker" GUI tool no longer works properly with newer versions of macOS/OSX, I strongly advise you not to use that.

Title: How distribute OSX cli / server app

Body:
Im building a cli app that can run in server mode for osx in golang. I come from the server world and have no idea how properly distribute a consumer cli tool for osx. The cli can run as a service which can be easily achieved with launchd.

Launchd config:

<plist version="1.0">
    <dict>
        <key>KeepAlive</key>
        <true/>
        <key>Label</key>
        <string>focus-daemon</string>
        <key>RunAtLoad</key>
        <true />
        <key>Program</key>
        <string>/usr/local/bin/focus</string>
  </dict>
</plist>

Building and running is also quite simple:

go build main.go
sudo cp main /usr/local/bin/focus
rm main
sudo chown root /usr/local/bin/focus
sudo chmod 4555 /usr/local/bin/focus
cp focus.plist ~/Library/LaunchAgents/com.21stio.focus.plist
launchctl load ~/Library/LaunchAgents/com.21stio.focus.plist

When being build the process requires sudo to set a sbit on the binary.

I don't want the user having to run a .sh script. Maybe I could use brew and/or a DMG for that. But I have no idea how I can put the Launchd config at the right spot then.


问:
apache nifi , hdfs parquet format
I am a newbie to NIFI, my use case is to read from a port and write to hdfs in parquet format, my research says there is something called KiteSDK, with which I can save as Parquet format.Am I right ?.Please advice.Any examples would help.</p>

答: You can use the PutParquet processor of NiFi to do so. (Type PutParquet in "the filter input field": hyperlink under Processors.)

Title: apache nifi , hdfs parquet format

ContentLicense: CC BY-SA 4.0


问:
update fancybox current slide content on button click
I want to update content of current slide on according to content type.
If I try setting content, instead of showing pdf or image it only shows html string.

Here is my code:

```<code>    $("#fancywork-manual-b").click(function() {
  $.fancybox.open([{
        src: '<a id="btn_click" class="btn" href="#">clickme</a>',
        type: 'html',
        smallBtn: false,
        buttons: [
          'close',
          'fullScreen'
        ]

      }

    ],

    {
      afterShow: function(instance) {
        $("#btn_click").click(function() {
          $.fancybox.getInstance().setContent($.fancybox.getInstance().current, 'https://source.unsplash.com/ndjyaOp0fOc/1600x900');
        })
      }
    }

  );
});
</code>```

CodePen

Any help is appreciated. Thanks

答:
You have 2 options:

1) Open new instance and close current one:

```<code>afterShow: function(instance) {
    $("#btn_click").click(function() {

        $.fancybox.open({
            src : 'https://source.unsplash.com/ndjyaOp0fOc/1600x900',
            type : 'image'
        });

        instance.close();
    });

}
</code>```

2) If you really want to reuse current instance, you would need to update group and slide objects. It would be easier to completely replace both and then use jumpTo method to activate:

```<code>afterShow: function(instance) {
    $("#btn_click").click(function() {

        var f = $.fancybox.getInstance();

        f.group  = [];
        f.slides = {};

        f.createGroup({
            src : 'https://source.unsplash.com/ndjyaOp0fOc/1600x900',
            type : 'image'
        });

        f.jumpTo( 0 )

    })
}
</code>```

Demo - https://codepen.io/anon/pen/QOgPzy?editors=1010

Body:
I want to update content of current slide on according to content type.
If I try setting content, instead of showing pdf or image it only shows html string.

Here is my code:

    $("#fancywork-manual-b").click(function() {
  $.fancybox.open([{
        src: 'clickme',
        type: 'html',
        smallBtn: false,
        buttons: [
          'close',
          'fullScreen'
        ]

      }

    ],

    {
      afterShow: function(instance) {
        $("#btn_click").click(function() {
          $.fancybox.getInstance().setContent($.fancybox.getInstance().current, 'https://source.unsplash.com/ndjyaOp0fOc/1600x900');
        })
      }
    }

  );
});

CodePen

Any help is appreciated. Thanks

Body:
You have 2 options:

1) Open new instance and close current one:

afterShow: function(instance) {
    $("#btn_click").click(function() {

        $.fancybox.open({
            src : 'https://source.unsplash.com/ndjyaOp0fOc/1600x900',
            type : 'image'
        });

        instance.close();
    });

}

2) If you really want to reuse current instance, you would need to update group and slide objects. It would be easier to completely replace both and then use jumpTo method to activate:

afterShow: function(instance) {
    $("#btn_click").click(function() {

        var f = $.fancybox.getInstance();

        f.group  = [];
        f.slides = {};

        f.createGroup({
            src : 'https://source.unsplash.com/ndjyaOp0fOc/1600x900',
            type : 'image'
        });

        f.jumpTo( 0 )

    })
}

Demo - https://codepen.io/anon/pen/QOgPzy?editors=1010


问:
Left join not working in codeigniter
I written query to get record from main table tpl_upload_csv_file and get related record from tbl_process_csv. I get all the records but the problem is if i have 1 id from tpl_upload_csv_file in tbl_process_csv for 5 rows its displaying 5 times. Same record is displaying 5 times.

```<code>$this->db->select('tbl_process_csv.id, tbl_process_csv.record_no, tbl_process_csv.reason,tpl_upload_csv_file.uploaded_file_name, tpl_upload_csv_file.uploaded_date_time');
$this->db->from('tpl_upload_csv_file');
$this->db->where('tbl_process_csv.process_status', 3);
$this->db->join('tbl_process_csv', 'tbl_process_csv.csv_file_id = tpl_upload_csv_file.id', 'left');
$this->db->order_by('tbl_process_csv.date_of_processing', 'desc');
$query = $this->db->get();
print_r($query->result());die;
return $query->result();
</code>```

My table structure is

tpl_upload_csv_file :

id

uploaded_file_name

uploaded_date_time

records_available

tbl_process_csv :

id

csv_file_id   -->(Reference if for table tpl_upload_csv_file)

record_no

process_status

reason

答:
```<code>$this->db->distinct('tbl_process_csv.id');
</code>```

Add this line in your code.

So, you will get distinct records w.r.t tbl_process_csv.id

Title: Left join not working in codeigniter

Body:
I written query to get record from main table tpl_upload_csv_file and get related record from tbl_process_csv. I get all the records but the problem is if i have 1 id from tpl_upload_csv_file in tbl_process_csv for 5 rows its displaying 5 times. Same record is displaying 5 times.

$this->db->select('tbl_process_csv.id, tbl_process_csv.record_no, tbl_process_csv.reason,tpl_upload_csv_file.uploaded_file_name, tpl_upload_csv_file.uploaded_date_time');
$this->db->from('tpl_upload_csv_file');
$this->db->where('tbl_process_csv.process_status', 3);
$this->db->join('tbl_process_csv', 'tbl_process_csv.csv_file_id = tpl_upload_csv_file.id', 'left');
$this->db->order_by('tbl_process_csv.date_of_processing', 'desc');
$query = $this->db->get();
print_r($query->result());die;
return $query->result();

My table structure is

tpl_upload_csv_file :

id

uploaded_file_name

uploaded_date_time

records_available

tbl_process_csv :

id

csv_file_id   -->(Reference if for table tpl_upload_csv_file)

record_no

process_status

reason

Body:
$this->db->distinct('tbl_process_csv.id');

Add this line in your code.

So, you will get distinct records w.r.t tbl_process_csv.id


问:
System.ComponentModel.InotifyPropertyChanging error
I am developing a windows form app that will need to run on a production machine that is only running .net 2.0.

in this project i am, however, using some 3.0+ related classes (ie linq) , therefore even know i have set the target framework to 2.0 in visual studio, i have copied all 3.0+ related dlls to to production server but i am getting the following error when i am working with multi threating  any idea why ?

```<code>System.ComponentModel.INotifyPropertyChanging' from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
</code>```

here are the list of dlls i have copied to release folder

System.dll

System.Core.dll

System.Data.dll

System.Data.Linq.dll

System.Deployment.dll

System.Windows.Forms.dll

as you can see i have copied the latest version of System.dll to the target folder but the app seems to be using the one installed on machine and ignore mine

any help would greatly be appreciated

thanks

答:
ok this seems to work :)

Assembly Redirect

Body:
I am developing a windows form app that will need to run on a production machine that is only running .net 2.0.

in this project i am, however, using some 3.0+ related classes (ie linq) , therefore even know i have set the target framework to 2.0 in visual studio, i have copied all 3.0+ related dlls to to production server but i am getting the following error when i am working with multi threating  any idea why ?

System.ComponentModel.INotifyPropertyChanging' from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

here are the list of dlls i have copied to release folder

System.dll

System.Core.dll

System.Data.dll

System.Data.Linq.dll

System.Deployment.dll

System.Windows.Forms.dll

as you can see i have copied the latest version of System.dll to the target folder but the app seems to be using the one installed on machine and ignore mine

any help would greatly be appreciated

thanks


问:
Clone rep:policy on AEM
I am currently working on with a solution that would be able to clone/copy/backup my existing rep:policy. 'Cause when we do some jobs it accidentally removed. I am trying to apply this kind of fix, but am failing to. It says it is an invalid path.

javax.jcr.security.AccessControlException: OakAccessControl0006: Isolated policy node. Parent is not of type [rep:AccessControllable]

```<code>        final Workspace ws = session.getWorkspace();
           ws.copy("/etc/commerce/products/abccompany/TvPackChannelMap/rep:policy","/tmp/nxt/TvPackChannelMap/rep:policy");
</code>```

Are there other ways that I can be able to take the rep:policy thru code?

答: You can check, install and use the access control tool from netcentric. It offers a jmx interface for exporting AC entries and maybe also some APIs you could use to implement your custom solution.</p>

Title: Clone rep:policy on AEM

Body:
I am currently working on with a solution that would be able to clone/copy/backup my existing rep:policy. 'Cause when we do some jobs it accidentally removed. I am trying to apply this kind of fix, but am failing to. It says it is an invalid path.

javax.jcr.security.AccessControlException: OakAccessControl0006: Isolated policy node. Parent is not of type [rep:AccessControllable]

        final Workspace ws = session.getWorkspace();
           ws.copy("/etc/commerce/products/abccompany/TvPackChannelMap/rep:policy","/tmp/nxt/TvPackChannelMap/rep:policy");

Are there other ways that I can be able to take the rep:policy thru code?


问:
Summing one ArrayList of Integers to another ArrayList of Integers, gives error: variable expected
I have two ArrayList of 6 elements in my Android application. Let's call them ArrayList "A" and "B". Each object in my class has this line in the constructor:

```<code>likes = new ArrayList<Integer>();
</code>```

I could also add this line in the constructor (I'm not sure which one is better, but I want to initialize the size to 6, and all elements should be 0):

```<code>likes = new ArrayList<>(Collections.nCopies(6, 0));
</code>```

I have a method in my class called Calculate, which is supposed to take a new ArrayList of Integers, B, of the same size as A, as a parameter. Then add / sum B with this object's ArrayList, A.

Here is the method:

```<code>public void Calculate(ArrayList<Integer> likes){
    for(int i = 0; i < likes.size(); i++){
        this.likes.get(i) += likes.get(i);
        //this.likes.get(i) = 3;
    }
}
</code>```

I'm getting a red line under the line this.likes.get(i), saying:

Variable Expected

Even if I try to just say this.likes.get(i) = 3; I get the same error.

Let's say A = {0,0,0,0,0,0}, and B = {1,0,0,-1,1,0}

What is the correct way to sum to ArrayList, to make A = {1,0,0,-1,1,0}?

答:
You are trying to use incorrectly the get method (used only to retrieve data), instead you must use the set method to assign a value in the ArrayList

```<code>public void Calculate(ArrayList<Integer> likes){
    for(int i = 0; i < likes.size(); i++){
        this.likes.set(i, (this.likes.get(i) + likes.get(i));
        //this.likes.set(i, 3);
    }
}
</code>```

Body:
I have two ArrayList of 6 elements in my Android application. Let's call them ArrayList "A" and "B". Each object in my class has this line in the constructor:

likes = new ArrayList<Integer>();

I could also add this line in the constructor (I'm not sure which one is better, but I want to initialize the size to 6, and all elements should be 0):

likes = new ArrayList<>(Collections.nCopies(6, 0));

I have a method in my class called Calculate, which is supposed to take a new ArrayList of Integers, B, of the same size as A, as a parameter. Then add / sum B with this object's ArrayList, A.

Here is the method:

public void Calculate(ArrayList<Integer> likes){
    for(int i = 0; i < likes.size(); i++){
        this.likes.get(i) += likes.get(i);
        //this.likes.get(i) = 3;
    }
}

I'm getting a red line under the line this.likes.get(i), saying:

Variable Expected

Even if I try to just say this.likes.get(i) = 3; I get the same error.

Let's say A = {0,0,0,0,0,0}, and B = {1,0,0,-1,1,0}

What is the correct way to sum to ArrayList, to make A = {1,0,0,-1,1,0}?

Body:
You are trying to use incorrectly the get method (used only to retrieve data), instead you must use the set method to assign a value in the ArrayList

public void Calculate(ArrayList<Integer> likes){
    for(int i = 0; i < likes.size(); i++){
        this.likes.set(i, (this.likes.get(i) + likes.get(i));
        //this.likes.set(i, 3);
    }
}


问:
Not logging in with requests.session()
I used requests library to log in to a website. I tried with scrapy, it is working fine. but when i try with requests, it is not working. I am getting the content of main page but not the page after logging in. when i print the url after post() method, i am not getting correct url. The code is below

```<code>    import requests
from bs4 import BeautifulSoup
r=requests.get("http://collegekart.in/login")
c=r.content
soup=BeautifulSoup(c,"html.parser")
token=soup.find("meta",{"name":"csrf-token"})
print(token)
tok=token['content']
print(tok)
s=requests.session()
login={"username":'fdgdgfdgdfgdfg@gmail.com',"password":'dgfdgdfgfdgdfgd',"csrf-token":tok}
s.post("http://collegekart.in/login",data=login)
t=s.get("http://collegekart.in/users")
print(t.url)
sop=BeautifulSoup(t.content,"html.parser")
print(sop.prettify())
</code>```

I am getting the output content of "collegekart.in" instead of "collegekart.in/users.

答:
Give this a go. You have done lots of unnecessary stuffs to do a simple task. However, when you get logged in, you can find that webpage displaying some items. I've scraped the title as well.

```<code>import requests
from bs4 import BeautifulSoup

payload={

'utf8':'✓',
'username':'zerqqr1@iydhp.com',
'password':'hanfenghanfeng'
}

res = requests.get("http://collegekart.in/access/attempt_login?",headers={'User-Agent':'Mozilla/5.0'},params=payload)
soup = BeautifulSoup(res.text,"lxml")
for item in soup.find_all(class_="title"):
    print(item.text)
</code>```

Partial output from populated results:

```<code>Enriching Speakjng and Writing Skills
Engineering Chemistry 16th edition
A Textbook of Engineering Physics
</code>```

Title: Not logging in with requests.session()

Body:
I used requests library to log in to a website. I tried with scrapy, it is working fine. but when i try with requests, it is not working. I am getting the content of main page but not the page after logging in. when i print the url after post() method, i am not getting correct url. The code is below

    import requests
from bs4 import BeautifulSoup
r=requests.get("http://collegekart.in/login")
c=r.content
soup=BeautifulSoup(c,"html.parser")
token=soup.find("meta",{"name":"csrf-token"})
print(token)
tok=token['content']
print(tok)
s=requests.session()
login={"username":'fdgdgfdgdfgdfg@gmail.com',"password":'dgfdgdfgfdgdfgd',"csrf-token":tok}
s.post("http://collegekart.in/login",data=login)
t=s.get("http://collegekart.in/users")
print(t.url)
sop=BeautifulSoup(t.content,"html.parser")
print(sop.prettify())

I am getting the output content of "collegekart.in" instead of "collegekart.in/users.

Body:
Give this a go. You have done lots of unnecessary stuffs to do a simple task. However, when you get logged in, you can find that webpage displaying some items. I've scraped the title as well.

import requests
from bs4 import BeautifulSoup

payload={

'utf8':'✓',
'username':'zerqqr1@iydhp.com',
'password':'hanfenghanfeng'
}

res = requests.get("http://collegekart.in/access/attempt_login?",headers={'User-Agent':'Mozilla/5.0'},params=payload)
soup = BeautifulSoup(res.text,"lxml")
for item in soup.find_all(class_="title"):
    print(item.text)

Partial output from populated results:

Enriching Speakjng and Writing Skills
Engineering Chemistry 16th edition
A Textbook of Engineering Physics


问:
Check if current user is administrator in wordpress
I am developing a plugin for wordpress, I want to find if current user is administrator or not, unfortunately I could not use the current_user_can() as it gives me error, so am using the global $current_user. But I could not get inside the if part even for admin user.. How to fix this?

```<code>global $current_user;
if ($current_user->role[0]=='administrator'){
function hide_post_page_options() {
//global $post;
// Set the display css property to none for add category and add tag functions
$hide_post_options = "<style type=\"text/css\"> .jaxtag { display: none; } #category-adder { display: none; } </style>";
print($hide_post_options);
}
add_action( 'admin_head', 'hide_post_page_options'  );
}
</code>```

答:
```<code>$user=wp_get_current_user();
if(in_array("administrator", $user->roles)){
  //user role is admin
}
</code>```

Body:
I am developing a plugin for wordpress, I want to find if current user is administrator or not, unfortunately I could not use the current_user_can() as it gives me error, so am using the global $current_user. But I could not get inside the if part even for admin user.. How to fix this?

global $current_user;
if ($current_user->role[0]=='administrator'){
function hide_post_page_options() {
//global $post;
// Set the display css property to none for add category and add tag functions
$hide_post_options = "";
print($hide_post_options);
}
add_action( 'admin_head', 'hide_post_page_options'  );
}


问:
how to generically compare entire java beans?
I've been trying to grok the org.apache.commons.beanutils library for a method/idiom to evaluate for equality all properties between 2 instances i.e. a generic equals() method for beans.

Is there a simple way to do this usnig this library? Or am I going about this the wrong way?
Thanks.

答: As mentioned above, a reflection-based implementation will do what you want. I just wanted to warn you, that reflection is quite costly and such an implementation could be comparably slow. If you just need to do occasional comparisons, you will be fine. However, if you have huge datasets and frequent equality checks (e.g. filtering of big tables) you might get into trouble.</p>

OwnerDisplayName: netzwerg


问:
NHibernate increment column that isn't id
I would like the db to auto increment an EmployeeId # for me. This would be a business id, and not the same as the db id (which is hilo generated). I found what looks like a promising solution but am having a problem implementing it.

I can't tell if the exception I'm getting is because the mapping is incorrect, SQLite can't handle it, or something else. I would also like to know if anyone has a different solution to this.

Cheers,

Berry

MAPPING

```<code><class name="Resource" table="Resources" ...>

<id name="Id" type="System.Int32" unsaved-value="0">
  <column name="ResourceId" />
  <generator class="hilo" />
</id>
...
  <component name="EmployeeNumber" unique="true">
    <property name="StorageValue" generated="always" insert="false">
      <column name="EmployeeNumber" />
    </property>
  </component>
  ...
 </class>

 <database-object>
<create>
  ALTER TABLE Entity DROP COLUMN EmployeeNumber
  ALTER TABLE Entity ADD EmployeeNumber INT IDENTITY
</create>
<drop>
  ALTER TABLE Entity DROP COLUMN EmployeeNumber
</drop>
</database-object>
</code>```

EXCEPTION output

```<code>ALTER TABLE Entity DROP COLUMN EmployeeNumber
  ALTER TABLE Entity ADD EmployeeNumber INT IDENTITY

ALTER TABLE Entity DROP COLUMN EmployeeNumber
  ALTER TABLE Entity ADD EmployeeNumber INT IDENTITY
failed: System.Exception : Generate schema error:
----> System.Data.SQLite.SQLiteException : SQLite error
near "DROP": syntax error
NHibernate\DbConfiguration\NHibInitialization\SchemaManager.cs(58,0): at Smack.Core.Data.NHibernate.DbConfiguration.NHibInitialization.SchemaManager._generateNewDb(Configuration cfg, IDbConnection conn)
NHibernate\DbConfiguration\NHibInitialization\SchemaManager.cs(16,0): at Smack.Core.Data.NHibernate.DbConfiguration.NHibInitialization.SchemaManager.GenerateNewDb(Configuration cfg, IDbConnection connection)
NHibernate\TestFixtures\SQLite\SQLiteBaseTestFixture.cs(56,0): at Smack.Core.TestingSupport.NHibernate.TestFixtures.SQLite.SQLiteBaseTestFixture._buildSchema()
NHibernate\TestFixtures\SQLite\SQLiteBaseTestFixture.cs(37,0): at Smack.Core.TestingSupport.NHibernate.TestFixtures.SQLite.SQLiteBaseTestFixture._SetUpNHibernateSession()
NHibernate\TestFixtures\SQLite\SQLiteBaseTestFixture.cs(25,0): at Smack.Core.TestingSupport.NHibernate.TestFixtures.SQLite.SQLiteBaseTestFixture.OnSetUp()
Mappings\EmployeeMappingTests.cs(23,0): at Smack.ConstructionAdmin.Data.Tests.Mappings.EmployeeMappingTests.OnSetUp()
BaseTestFixture.cs(27,0): at Smack.Core.TestingSupport.BaseTestFixture.SetUp()
--SQLiteException
at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String& strRemain)
at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
</code>```

答: In the flow chart for the ALTER TABLE SQLite statement here, I cannot find a DROP clause. You can only add and rename columns. So, you could rename EmployeeNumber to EmployeeNumber_old instead of dropping it. You could also drop and recreate the whole table (but if this is a persistent SQLite DB containing production data, I would advise against it)</p>

Body:
I would like the db to auto increment an EmployeeId # for me. This would be a business id, and not the same as the db id (which is hilo generated). I found what looks like a promising solution but am having a problem implementing it.

I can't tell if the exception I'm getting is because the mapping is incorrect, SQLite can't handle it, or something else. I would also like to know if anyone has a different solution to this.

Cheers,

Berry

MAPPING

<class name="Resource" table="Resources" ...>

<id name="Id" type="System.Int32" unsaved-value="0">
  <column name="ResourceId" />
  <generator class="hilo" />
</id>
...
  <component name="EmployeeNumber" unique="true">
    <property name="StorageValue" generated="always" insert="false">
      <column name="EmployeeNumber" />
    </property>
  </component>
  ...
 </class>

 <database-object>
<create>
  ALTER TABLE Entity DROP COLUMN EmployeeNumber
  ALTER TABLE Entity ADD EmployeeNumber INT IDENTITY
</create>
<drop>
  ALTER TABLE Entity DROP COLUMN EmployeeNumber
</drop>
</database-object>

EXCEPTION output

ALTER TABLE Entity DROP COLUMN EmployeeNumber
  ALTER TABLE Entity ADD EmployeeNumber INT IDENTITY

ALTER TABLE Entity DROP COLUMN EmployeeNumber
  ALTER TABLE Entity ADD EmployeeNumber INT IDENTITY
failed: System.Exception : Generate schema error:
----> System.Data.SQLite.SQLiteException : SQLite error
near "DROP": syntax error
NHibernate\DbConfiguration\NHibInitialization\SchemaManager.cs(58,0): at Smack.Core.Data.NHibernate.DbConfiguration.NHibInitialization.SchemaManager._generateNewDb(Configuration cfg, IDbConnection conn)
NHibernate\DbConfiguration\NHibInitialization\SchemaManager.cs(16,0): at Smack.Core.Data.NHibernate.DbConfiguration.NHibInitialization.SchemaManager.GenerateNewDb(Configuration cfg, IDbConnection connection)
NHibernate\TestFixtures\SQLite\SQLiteBaseTestFixture.cs(56,0): at Smack.Core.TestingSupport.NHibernate.TestFixtures.SQLite.SQLiteBaseTestFixture._buildSchema()
NHibernate\TestFixtures\SQLite\SQLiteBaseTestFixture.cs(37,0): at Smack.Core.TestingSupport.NHibernate.TestFixtures.SQLite.SQLiteBaseTestFixture._SetUpNHibernateSession()
NHibernate\TestFixtures\SQLite\SQLiteBaseTestFixture.cs(25,0): at Smack.Core.TestingSupport.NHibernate.TestFixtures.SQLite.SQLiteBaseTestFixture.OnSetUp()
Mappings\EmployeeMappingTests.cs(23,0): at Smack.ConstructionAdmin.Data.Tests.Mappings.EmployeeMappingTests.OnSetUp()
BaseTestFixture.cs(27,0): at Smack.Core.TestingSupport.BaseTestFixture.SetUp()
--SQLiteException
at System.Data.SQLite.SQLite3.Prepare(SQLiteConnection cnn, String strSql, SQLiteStatement previous, UInt32 timeoutMS, String& strRemain)
at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()