text:
Q: Corrupt or corrupted? Should I say "the thing is corrupted" or "the thing is corrupt"?
Would they carry different meanings?
i.e "My hard drive is corrupted, so all of my information is lost" vs "My hard drive is corrupt, so all my information is lost".
I know that for a politician (for instance), one would use the present tense, i.e "The Mayor is corrupt and is ruining the city", but what about things?

A: Corrupt and corrupted have similar/overlapping meanings in general, as corrupt comes from a Latin past (passive) participle and corrupted is (or at least, is derived from) an English past (passive) participle.
"Corrupted by..." cannot be replaced with "corrupt by..."
One difference I can think of is that "corrupted by [agent/instrument]" is a common construction, but "corrupt by [agent/instrument]" is extremely questionable (although apparently it has been used by certain authors).
E.g. the two following sentences sound natural:

*

*"He is corrupted by power."

*"The file was corrupted by a virus."

But the next two don't:

*

*"*He is corrupt by power."

*"*The file was corrupt by a virus."

"Corrupt by..." certainly may be acceptable when the by-phrase doesn't designate an agent or instrument; e.g. "corrupt by nature" and "corrupt by design" sound OK.
Interestingly, "corrupt by" used to be used to mean "corrupted by"
The Oxford English Dictionary mentions that corrupt was once used in English as a participle, and gives (among others) the following example from Shakespeare:

*

*
1609   Shakespeare Sonnets cxxxvii. sig. Iv   Eyes corrupt by ouer-partiall lookes.

Google Books also supplies a few examples of "corrupt by power" and "was corrupt by [instrument/agent]" from some old texts:

*

*
Oh, man ! thou feeble tenant of an hour, Dehas'd by slavery, or corrupt by power,
Who knows thee well, must quit thee with disgust, Degraded mass of animated dust

Byron's "Curious Epitaph on a Dog," printed in Annual gleanings of wit and humour, by a celebrated wit of the age (1816)

*
All flesh was corrupt by its iniquities.

Chapter III,
Nicene and Post-Nicene Fathers: Second Series, Volume X: Ambrose Select Works and Letters, edited by Philip Schaff & Rev. Henry Wallace, originally published 1896, translated by the Rev. H. De Romestin

*
Then Noah, righteous and perfect, walked with God, that is in his laws, and the earth was corrupt by sin and filled. When God saw the earth to be corrupt, and that every man was corrupt by sin upon the earth

"Noah", The Golden Legend: Lives of the Saints, compiled by Jacobus de Voragine, 1275; first translated by William Caxton, 1483; from the Temple Classics edited by F.S. Ellis (first edition 1900); re-typeset and republished in 2015 by Catholic Way Publishing
However, none of these sound grammatical to me, a speaker of modern English.

A: Looking at a dictionary entry, there are several definitions for corrupt as both verb and adjective; they seem to cover the same sorts of problems.
Ordinarily, "corrupted" should be emphasizing more that this is something that happened as opposed to the present state.  If we say "The leader was corrupted," we start wondering when it happened, who corrupted him, how, etc.  "The leader was corrupt" simply describes how he is now.
But computer tech is different.  I've never heard someone say a hard drive was "corrupt," but only "corrupted."  I'd think of a part of computer memory, a storage medium, or a file as corrupted if it has some damage and corrupt if it's essentially garbage.  This isn't rational, but it's what feels right to me.  (My expertise is in computers.)  Sometimes the newer uses of a word take a while to settle down in their usage, I think.

A: In Portuguese, we have "corrupto" and "corrompido", the former - adjective -  describing someone (necessarily an entity, never inanimate objects) as liable to corruption, and the latter - adjective or verb - assigning a state of effective corruption to any subject, regardless of its nature.


text:
Q: Why can't this etherum tx input data be decoded? If you go to this transaction page on etherscan, scroll down to the Input Data section and click the Decode Input Data button- it gives you nothing, which I can only assume means that etherscan was unable to decode the input data given the ABI for that contract.
My question is, why? What is special about that contract/ABI (or really any contract like this one) that would prevent the transaction from being decoded?

A: The called function signagure is 0xfaa916d3, the rest of the data are arguments. The contract ABI doesn't define any function that would translate to the 0xfaa916d3 signature. Which means that the fallback function was called.
In this case, the fallback function acts as a proxy, creates an internal transaction and delegates the call to the target contract (which can theretically do the same or create multiple other internal transactions, etc.)
However, Etherscan currently only compares the signature to the ABI of the root transaction recipient and ignores the internal transactions recipients' ABIs in the "Decode input data" feature.
Why? My guess is that it's easier to scan just one level, and not that high priority to implement and account for all the edge cases such as multiple internal calls with the same signature. But you'd need to ask them for the real reason. :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve a single field from a table in laravel 5.2 $price = DB::table('price')
       ->where([
        ['days_id', $days AND 'deals_id', $selected_deal] ])
       ->pluck('price');

I'm using this code to get single price only but it give me all prices where these to conditions are coming.
Record in database:

A: Using value() method you can get single value/field from the table you want
$price = DB::table('price')
       ->where([
        ['days_id', $days AND 'deals_id', $selected_deal] ])
       ->value('price');

A: As you can read here

The pluck method retrieves all of the values for a given key

I don't know what do you exactly want to achieve but you should to take a look on first, last or filter method. If think the last one will be the best for you.


text:
Q: Spark csv to dataframe skip first row I am loading csv to dataframe using -
sqlContext.read.format("com.databricks.spark.csv").option("header", "true").
                option("delimiter", ",").load("file.csv")

but my input file contains date in the first row and header from  second row.
example
20160612
id,name,age
1,abc,12
2,bcd,33

How can i skip this first row while converting csv to dataframe?

A: Here are several options that I can think of since the data bricks module doesn't seem to provide a skip line option:
Option one: Add a "#" character in front of the first line, and the line will be automatically considered as comment and ignored by the data.bricks csv module;
Option two: Create your customized schema and specify the mode option as DROPMALFORMED which will drop the first line since it contains less token than expected in the customSchema:
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType};

val customSchema = StructType(Array(StructField("id", IntegerType, true),
                                    StructField("name", StringType, true),
                                    StructField("age", IntegerType, true)))

val df = sqlContext.read.format("com.databricks.spark.csv").
                         option("header", "true").
                         option("mode", "DROPMALFORMED").
                         schema(customSchema).load("test.txt")

df.show

16/06/12 21:24:05 WARN CsvRelation$: Number format exception. Dropping
  malformed line: id,name,age

+---+----+---+
| id|name|age|
+---+----+---+
|  1| abc| 12|
|  2| bcd| 33|
+---+----+---+

Note the warning message here which says dropped malformed line:
Option three: Write your own parser to drop the line that doesn't have length of three:
val file = sc.textFile("pathToYourCsvFile")

val df = file.map(line => line.split(",")).
              filter(lines => lines.length == 3 && lines(0)!= "id").
              map(row => (row(0), row(1), row(2))).
              toDF("id", "name", "age")

df.show
+---+----+---+
| id|name|age|
+---+----+---+
|  1| abc| 12|
|  2| bcd| 33|
+---+----+---+


text:
Q: How can I get pandas' groupby command to return a DataFrame instead of a Series? I don't understand the output of pandas' groupby. I started with a DataFrame (df0) with 5 fields/columns (zip, city, location, population, state).
 >>> df0.info()
 <class 'pandas.core.frame.DataFrame'>
 RangeIndex: 29467 entries, 0 to 29466
 Data columns (total 5 columns):
 zip      29467 non-null object
 city     29467 non-null object
 loc      29467 non-null object
 pop      29467 non-null int64
 state    29467 non-null object
 dtypes: int64(1), object(4)
 memory usage: 1.1+ MB

I wanted to get the total population of each city, but since several cities have multiple zip codes, I thought I would use groupby.sum as follows:
  df6 = df0.groupby(['city','state'])['pop'].sum()

However, this returned a Series instead of a DataFrame:
 >>> df6.info()
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 2672, in __getattr__
     return object.__getattribute__(self, name)
  AttributeError: 'Series' object has no attribute 'info'
 >>> type(df6)
 <class 'pandas.core.series.Series'>

I would like to be able look up the population of any city with a method similar to
 df0[df0['city'].isin(['ALBANY'])]

but since I have a Series instead of a DataFrame, I can't. I haven't been able to force a conversion into a DataFrame either.
What I'm now wondering is:

*

*Why didn't I get a DataFrame back instead of a Series?

*How can I get a table that will let me look up the population of a city? Can I use the Series I got from groupby, or should I have taken a different approach?

A: Need parameter as_index=False in groupby or reset_index for convert MultiIndex to columns:
df6 = df0.groupby(['city','state'], as_index=False)['pop'].sum()

Or:
df6 = df0.groupby(['city','state'])['pop'].sum().reset_index()

Sample:
df0 = pd.DataFrame({'city':['a','a','b'],
                   'state':['t','t','n'],
                   'pop':[7,8,9]})

print (df0)
  city  pop state
0    a    7     t
1    a    8     t
2    b    9     n

df6 = df0.groupby(['city','state'], as_index=False)['pop'].sum()
print (df6)
  city state  pop
0    a     t   15
1    b     n    9

df6 = df0.groupby(['city','state'])['pop'].sum().reset_index()
print (df6)
  city state  pop
0    a     t   15
1    b     n    9

Last select by loc, for scalar add item():
print (df6.loc[df6.state == 't', 'pop'])
0    15
Name: pop, dtype: int64

print (df6.loc[df6.state == 't', 'pop'].item())
15

But if need only lookup table is possible use Series with MultiIndex:
s = df0.groupby(['city','state'])['pop'].sum()
print (s)
city  state
a     t        15
b     n         9
Name: pop, dtype: int64

#select all cities by : and state by string like 't'
#output is Series of len 1
print (s.loc[:, 't'])
city
a    15
Name: pop, dtype: int64

#if need output as scalar add item()
print (s.loc[:, 't'].item())
15

A: It's hard to say definitively without sample data, but with the code you show, returning a Series, you should be able to access the population for a city by using something like df6.loc['Albany', 'NY'] (that is, index your grouped Series by the city and state).
The reason you get a Series is because you selected a single column ('pop') on which to apply your group computation.  If you apply your group computation to a list of columns, you'll get a DataFrame.  You could do this by doing df6 = df0.groupby(['city','state'])[['pop']].sum().  (Note the extra brackets around 'pop', to select a list of one column instead of a single column.)  But I'm not sure there's a reason to do this if you can use the above method to access the city data anyway.


text:
Q: Do routers need to have assigne IP from given VLAN to foward VLAN packages? (sorry for my basic question but I had noone to ask)
Does routers/smart-switches that foward/pass vlan packets inside same network need to have assign IP from that given VLAN that they foward packets (thru TRUNK port) or they only need one IPfrom management VLAN so administrator can access them from that single VLAN ?

A: Routers need an IP address in every connected network they have to route from/to.
Switches, whether smart or not, only need an IP address for management, none in the networks they forward packets from/to.

A: "Assigned IP" could mean a few different things.
When I use the term, I only use that for when a system always has a fixed, known IP address.
However, the DHCP protocol (which decades ago I helped develop), is there to "assign" IP addresses for all nodes that don't have one already appointed to them.
Surely EVERY node needs an IP address, and they get that address the one way or the other. As soon as they have such an address, and presuming it's known to the routing systems / software (VPN, "VLAN" or otherwise), then it can communicate anything it wants. What happens from there depends on a lot of other factors such as open ports and so forth...


text:
Q: How to identify and merge columns in R data frame with adjacent column? I have reaction time data from an experiment in wide format where every row shows the data from a different participant. Every column gives information about a question (q01, q02 etc.) that was asked, e.g.:
   q01_response  q01_RT  q01_complete  q01_button  q02_response  q02_RT ...
1  yes           231     yes           m           yes           459
2  no            242     yes           c           yes           693

I would like to merge every question's response column (e.g., q01_response) with that same question's reaction time (e.g., q01_RT), while leaving the remaining columns as they are. The two columns I want to merge are always adjacent. Thus, I'd want the data frame to look like this:
   q01_responsexRT  q01_complete  q01_button  q02_responsexRT ...
1  yesx231          yes           m           yesx459
2  nox242           yes           c           yesx693

I know how to do that for two specific columns:
df_new <- unite(df, "q01_responsexRT", c("q01_response","q01_RT"), sep="x")

But I'd like to avoid doing that for every single pair individually. Thanks!

A: Here's a way using tidyverse :
library(tidyverse)
df1 <- read.table(h=T, strin=F, text="
q01_response  q01_RT  q01_complete  q01_button  q02_response  q02_RT
1  yes           231     yes           m           yes           459
2  no            242     yes           c           yes           693")

mutate(df1, !!!map2_dfc(
  select(df1, ends_with("_response")),
  select(df1, ends_with("_RT")),
  paste, sep ="x")) %>%
  select(-ends_with("_RT")) %>%
  rename_at(vars(ends_with("_response")),paste0,"xRT")

#   q01_responsexRT q01_complete q01_button q02_responsexRT
# 1         yesx231          yes          m         yesx459
# 2          nox242          yes          c         yesx693

It assumes that you have the same number of response and RT columns and in the right order (i.e. it doesn't check the column prefixes).

*

*Our first select calls build 2 subsets of the data frames with the relevant suffixes

*map2_dfc iterates on these columns to paste them, keeping the names from the first data frame.

*!!! splices the resulting data frame into a list of q01_response =... etc

*Then we remove the extra columns and rename the newly updated ones

And here's a somewhat more "idiomatic" version, more robust as it looks at both prefixes and suffixes, containing a lot of gather / spread jiu-jitsu :
df1 %>%
  rowid_to_column() %>%
  gather(key,value, -rowid) %>%
  separate(key,c("q","key2"))  %>%
  spread(key2,value) %>%
  unite(responsexRT, response, RT, sep = "x") %>%
  gather(key2,value, -rowid, -q) %>%
  unite(key, q, key2, sep ="x") %>%
  spread(key,value) %>%
  select(-rowid)

#   q01xbutton q01xcomplete q01xresponsexRT q02xbutton q02xcomplete q02xresponsexRT
# 1          m          yes         yesx231       <NA>         <NA>         yesx459
# 2          c          yes          nox242       <NA>         <NA>         yesx693

A: You can also loop over the questions explicitly, if you know how many questions there are to process.
library("tidyverse")
library("glue")

example <- "
q01_response  q01_RT  q01_complete  q01_button  q02_response  q02_RT
yes           231     yes           m           yes           459
no            242     yes           c           yes           693
"

unite_response_time <- function(df, q) {
  in_cols <- c(glue("{q}_response"), glue("{q}_RT"))
  out_col <- glue("{q}_responsexRT")
  df %>% unite(!!out_col, in_cols, sep = "x")
}

df <- read_table(example)

for (q in c("q01", "q02")) {
  df <- unite_response_time(df, q)
}
df
#> # A tibble: 2 x 4
#>   q01_responsexRT q01_complete q01_button q02_responsexRT
#>   <chr>           <chr>        <chr>      <chr>
#> 1 yesx231         yes          m          yesx459
#> 2 nox242          yes          c          yesx693

# or

df <- read_table(example)

for (i in seq(2)) {
  q <- sprintf("q%02d", i)
  df <- unite_response_time(df, q)
}
df
#> # A tibble: 2 x 4
#>   q01_responsexRT q01_complete q01_button q02_responsexRT
#>   <chr>           <chr>        <chr>      <chr>
#> 1 yesx231         yes          m          yesx459
#> 2 nox242          yes          c          yesx693

Created on 2019-03-25 by the reprex package (v0.2.1)


text:
Q: SwiftUI ask Push Notifications Permissions again So I have push notifications implemented in my App and when the app first starts up, its asks users if they would like to allow push notifications (this implementation works fine as expected).
If this user disallows the push notifications, is it possible to have a button in the app which allows the user to click on and it would ask to allow permissions again?
This is what im trying to achieve:
SettingsView
//IF PUSH NOTIFICATIONS NOT ENABLED, SHOW THIS SECTION

Section (header: Text("Push Notifications")) {
                        HStack {
                            Image(systemName: "folder")
                                .resizable()
                                .frame(width: 20, height: 20)
                            VStack(alignment: .leading) {
                                Text("Enable Push Notifications").font(.callout).fontWeight(.medium)
                            }
                            Spacer()
                            Button(action: {
                                checkPushNotifications()
                            }) {
                                Text("View").font(.system(size:12))
                            }
                        }
                    }

In my Push Notification Function:
class PushNotificationService: NSObject, MessagingDelegate {

    static let shared = PushNotificationService()
    private let SERVER_KEY = "myserverkey"
    private let NOTIFICATION_URL = URL(string: "https://fcm.googleapis.com/fcm/send")!
    private let PROJECT_ID = "my project name"

    private override init() {
        super.init()
        Messaging.messaging().delegate = self
    }

    func askForPermission() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted: Bool, error: Error?) in
            if granted {
                self.refreshFCMToken()
            } else {
                // Maybe tell the user to go to settings later and re-enable push notifications
            }
        }
    }

    func refreshFCMToken() {
        InstanceID.instanceID().instanceID { (result, error) in
            if let error = error {
                print("Error fetching remote instance ID: \(error)")
            } else if let result = result {
                print("Remote instance ID token: \(result.token)")
                self.updateFCMToken(result.token)
            }
        }
    }

    func updateFCMToken(_ token: String) {
        guard let currentUser = Auth.auth().currentUser else { return }
        let firestoreUserDocumentReference = Firestore.firestore().collection("users").document(currentUser.uid)
        firestoreUserDocumentReference.updateData([
            "fcmToken" : token
        ])
    }
}

What im trying to achieve is if the user HAS NOT enabled notification only then ask them the option to reenable in SettingsView.

A: No you cannot. However, a good UI/UX design will be careful before burning the one-time chance of asking for permissions. Instead, use a user friendly UI to explain why you need certain permissions.  For example, I often found it frustrating to implement a permission display view, and handle various async permission requests in a seperate view model. So I recently made a SwiftUI package:
PermissionsSwiftUI

PermissionSwiftUI is a package to beautifully display and handle permissions.
EmptyView()
.JMPermissions(showModal: $showModal, for: [.locationAlways, .photo, .microphone])

For a SINGLE line of code, you get a beautiful UI and the permission dialogs.
It already supports 7 OUT OF 12 iOS system permissions. More features coming
Full example
struct ContentView: View {
    @State var showModal = false

    var body: some View {
        Button(action: {showModal=true},
               label: {Text("Ask user for permissions")})
           .JMPermissions(showModal: $showModal, for: [.locationAlways, .photo, .microphone])
       }
   }

To use PermissionsSwiftUI, simply add the JMPermission modifier to any view.
Pass in a Binding to show the modal view, and add whatever permissions you want to show.

A: The short answer is no, you can't ask the user again if he once disabled the push-notifications for your app.
What you can do, is navigating the user to the settings in their phone to allow push-notifications again.
The code snippet in SwiftUI for the button would be:
Button(action: {
    guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}, label: {
    Text("Allow Push")
})

I would also refer to this question: How to ask notifications permissions if denied?


text:
Q: How to implement forEach() in JSX - React Native for Custom Headers I am trying to create a method that returns a JSON object for custom headers to use with HTTPS requests. This should be defined as customHeaders={{headerKey: 'headerValue'}}
I am new to JSX and a little confused with my implementation of forEach loop here.
Here, this.props.httpHeaders passes a list of Keys and Values. The key is this.props.headerKey and corresponding value this.props.headerValue
The expected return is an Object that holds the key value pairs as {headerKey: 'headerValue'}
Here's my not so correct implementation. Can anyone explain me how to implement forEach() here? Thanks

 getCustomHeaders = () => {
        var customHeaders;
        let keyValueStr = "";
        if (this.isStatusAvailable(this.props.httpHeader) && this.isStatusAvailable(this.props.restURL)) {
            // Building Custom Headers input string
      this.props.httpHeader?.items?.forEach((element) => {
        const attrKey = this.props.headerKey.get(element);
        const attrValue = this.props.headerValue.get(element);
        if (keyValueStr !== "") {
          keyValueStr = keyValueStr.concat(",");
        }
        keyValueStr = keyValueStr+attrKey.value+": "+"'"+attrValue.value+"'";
      });
        }
        customHeaders = JSON.parse("{" + keyValueStr + "}");
        return customHeaders;
    };


text:
Q: Capture bitstream into string I'll need to capture my bitstream into a string and keep concatenating the string. However, I'm not really sure how it's to be done. Any ideas?
#include <bitset>
#include <iostream>
#include <string>

using namespace std;

int main ()
{

  int i;

  char data[30];
  int int_arr[30];

   printf("\nEnter the Data Bits to be transmitted : ");
 scanf("%s",data);

 // convert it into bitstream

 for (i=0; i<strlen(data); i++)
 {

  int_arr[i] = int(data[i]);
 }

 for (i=0; i<strlen(data); i++)
 {
  cout << int_arr[i]<<endl;
  cout << std::bitset<8>( int_arr[i] )<<endl; // Placeholder
 }

  return 0;
}

In the line where it's marked '//Placeholder', I really do not need to 'cout' it, rather, I'd have to capture the bitstream into a string and keep concatenating it.

A: std::stringstream?
#include <sstream>

std::string WriteSomethingToStringStream()
{
    std::ostringstream oss;
    oss << "foo?\n";
    oss << "bar!\n";
    return oss.str();
}


text:
Q: Memory failures when calling new It might be a little hard to explain everything about this error but I'll try my best. Unfortunately the code is so large that it would be unpractical to try to include it.
I am writing an academic OS for homework (nachos if you must know) and the most recent thing I needed to do was implement mutual exclusion in a core map. To do this I added a Lock and a condition variable per page in emulated main memory. After doing this I run my code and get through one call to the exception (in a completely different directory from core map) handler just fine, but the second time the function gets called I get and error on the following call: r=new Lock("read"); and it reads like this:
*** glibc detected *** /home/some_other_directories/workspace/nachos3_repo/vm/nachos: malloc(): memory corruption (fast): 0x0805fe20 ***

Just to see how it behaves I changed the allocation of that lock to be an extern in my system file (there are a lot of global externs there) and after that I get a seg fault on the call fout.open("old.txt"); which I traced back through the stack to be within a call to malloc in a call to new.
My best guess is that my heap is getting to large but I am not sure if that is the case or how to handle it if it is. can anyone shed light on this problem?

A: malloc is just the victim here. In some completely different part of the code you have written outside the allocated boundaries and thus have corrupted chain links that are used by the heap manager to track free/allocated blocks. As you try to allocate here, the heap manager is chasing these linked lists and lands into a protected area (most likely not allocated). You should do a review of your changes first and see if you can spot where you scribble the memory.


text:
Q: How to Format NSDate in the Model Layer I have a NSDate that I want to return as formatted like 10:00PM.
I have the date formatter working.
I'm wondering how I can make it so that whenever I fetch that date it comes back formatted as desired.
The NSDate in question in a daily start time for an activity that is store in an NSManagedObject
subclass.
@implementation Schedule

@dynamic repeat;
@dynamic start;

-(NSString*)amPMFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"h:mm a"];
    return [dateFormatter stringFromDate:self.start];
}

@end

I'm  using a keypath to fill in a TableViewCell. The object bound to the cell is a Ritual which knows a Schedule. My thought was to call the method amPMFormat using the keypath and just return the formatted date as a string but that doesn't work. This code is a cell created using Sensible TableView. The cell has a STEP bound to it, STEP has a SCHEDULE, and SCHEDULE has a start property which is an NSDate that only has hours and minutes saved into it.
SCCustomCell *descrCell = [SCCustomCell cellWithText:nil objectBindingsString:@"1:schedule.start.amPMFormat;3:desc" nibName:@"RitualCell"];

A: You've munged the Model and the View parts of your program.
The date (self.start) is an instant in time. You can represent that date in any of a multitude of calendars, languages, locale-specific formats, and precision. It's still a single instant in time.
The formatter is a way to build a standard string representation of that instant. If you want the date formatted a particular way "whenever [you] fetch that date", you can use -awakeFromFetch: to populate a read-only property. Or perhaps a class method on Schedule,  +formattedStringForDate:, which formats an NSDate appropriately and returns an NSString.
Your cryptic second snippet mentions "bindings". Are you using Cocoa Bindings and writing an OS X app? If so, you can put a date formatter on the NSTextField instance in your XIB.


text:
Q: Задача с переходом на новую страницу Делаю парсинг сайта собираю с него ссылки. Все отлично, но как мне сделать переход на новую страницу ,если я на странице собрал все ссылки.
Вот код:
for (int add = 1; true; add += 2) {
    var Request = new HttpRequest();
    string html;
    int countPage = 0;
    string htmlpath = String.Concat("http://test.ru/firms/?news=92000&grp=1%22&page=", countPage, "/");
    html = Request.Get(htmlpath).ToString();
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.OptionFixNestedTags = true; //Опционально, если требуется
    doc.Load(new StringReader(html));
    //В пути удалить tdata копировать в хроме
    string title = String.Concat("//body/div[1]/main/div[1]/table/tr/td[3]/div/table[2]/tr[", add, "]/td/table/tr/td[2]/a[@href]");
    var nodes = doc.DocumentNode.SelectNodes(title);
    if (nodes == null) // Здесь выкидывает из цикла, как все ссылки на странице собраны.
        break;

    StreamWriter sw = new StreamWriter(@"C:\\Test.txt", true);
    foreach(var node in nodes) {
      sw.WriteLine("http://test.ru" + node.Attributes["href"].Value);
    }
    sw.Close();
}

Но мне надо перезапустить цикл,только теперь еще нужно добавить к countPage +1, чтобы он собирал ссылки со следующей страницы. Я понимаю, что это редкостный говнокод, ну я только начал учить программинг.
Спасибо!

A: Оберните ваш код в еще один цикл
for (int page= 0; page< {сколько там всего страниц надо собрать}; page++)
{
    CollectLinksFromPage(page);
}

....

public void CollectLinksFromPage(int countPage)
{
    // тут весь код из вашего вопроса кроме строчки int countPage = 0;
}

A: Просто соберите ссылки в некий массив, да последовательно обойдите его, уже в другом цикле. Общий код для получения ссылок выделите в отдельный метод.
Если вам требуется собрать вообще все ссылки со всех страниц сайта(ну или на некую потенциально изменяемую глубину) - достаточно удобным будет использовать рекурсию.
Ну и просто совет - не используете для веб-скраппинга HAG. Его писали для разбора XHTML. В случае же с HTML - он практически всегда заставляет писать громоздкий, уродливый, и неэффективный код.


text:
Q: Forbid merging a pull request to a branch if the PR was not created from it The configurations of my application are kept in a git repository.
I use a separate branch for each environment e.g sandbox, UAT and PROD and they are completely different.
The problem is if a pull request branched from sandbox is mistakenly merged into prod branch, it will mess up the configurations there.
We enforce approval from reviewer for sure but to avoid any risk is there any way I can forbid merging a pull request to a branch if the PR was not created from that branch.
For example, if a pull request created from Sandbox, it will not be allowed to merge to UAT or PROD.


text:
Q: How to convert an image from SVG to PNG in Laravel I have searched a lot but did not find a working solution.
I have been trying to convert a QRcode SVG file to PNG format.
The following does return an empty black image but with no content. I would like to convert from the SVG format to PNG format with all the contents:
$file = SVG::fromFile(storage_path('app/public/qr_background.svg'));
    $background = $file->getDocument();

    $qrString = QrCode::size('2500')
        ->style('round')
        ->backgroundColor(0,0,0,1)
        ->generate(
            env('FARMCODE_BASE_URL')
            ? env('FARMCODE_BASE_URL') . $product->id
            : route('product-landingpage', ['product' => $product])
        );
    $qr = SVG::fromString($qrString)->getDocument();
    $qr->getChild(1)->setAttribute('transform', "translate(450,450) scale(44)");
    $background->addChild($qr);

    $name = 'abc.png';
    // Make image with Laravel Invervention package
    $image = Image::make($file->toRasterImage(2000,2000))->encode('png');
    $headers = [
        'Content-Type' => 'image/png',
        'Content-Disposition' => 'attachment; filename='. $name,
    ];
    return response()->stream(function() use ($image) {
        echo $image;
    }, 200, $headers);

I am using meyfa/php-svg simplesoftwareio/simple-qrcode and intervention/image


text:
Q: How can i create a multivariable function in matlab out of matrix data? but i want to make a program in which i can generate a function of multiple variables that depend on the number of rows of a matrix.
for k = 1:sizel;

f(k)=(alpha(k,1)+(beta(k,1)*p(k))+(gamma(k,1)*p(k)^2));

end

cost=(sum(f))

this is for the purpose of optimization so i need that at the end the variables are declares as p(1),p(2),p(3)... these will be the input for my function.
Note: i dont want to assign values to the variables because this will be done be the optimization algorithm in the optimization toolbox.
here is the complete code
function  cost = cost(p) ;
clc
clear

costfunctionconstantsmatrix;
sizel=size(CostFormulaconstants);

alpha=CostFormulaconstants(:,1);

beta=CostFormulaconstants(:,2);

gamma=CostFormulaconstants(:,3);

for k = 1:sizel;

f(k)=(alpha(k,1)+(beta(k,1)*p(k))+(gamma(k,1)*p(k)^2));

end

cost=(sum(f))

end

i used the symbolic approach and i got the correct answer for the cost indeed, i got something like this: (53*p(1))/10 + (11*p(2))/2 + (29*p(3))/5 + p(1)^2/250 + (3*p(2)^2)/500 + (9*p(3)^2)/1000 + 1100. But when i try to specify my function to be optimized in the optimization toolbox it tells me that the variables p are sym and cannot be converted to double. the trouble is how to convert this expression to double so that the optimization algorithm can input values for the variable p(1), p(2) and p(3)

A: Can you pass the matrix as an argument to the function?
function cost = fcn(my_mat)

[m,n] = size(my_mat);
f = zeros(m,1);
for k = 1:m % for example
   f(k)=(alpha(k,1)+(beta(k,1)*p(k))+(gamma(k,1)*p(k)^2));
end
cost = sum(f);

end

A: Your problem is not entirely clear to me but I believe you wish to generate a series of functions in which the variables alpha, beta, gamma are constants with different values for each function, and the vector p is an argument.
What confuses me in your question is that you use the index k for both the constants and the arguments, which I think is not what you intended to write. Assuming I understand your goal, a solution may make use of function handles.
The notation f(k) = @(p) p(1)+p(2) for example, generates a function that adds p(1) and p(2). Abbreviating CostFormulaconstants to cf, the following would generate a series of functions, one for each row in cf.
for k = 1 : size(cf, 1)
    f{k} = @(p) cf(k,1) + cf(k,2)*p(1) + cf(k,3)*p(2)^2;
end

You can supply individual function handles to callers from the optimization toolbox simply with f{3} for the third function, for example. A call to f{3} would look like
a = f{3}([3,4]);

If your functions are indeed all polynomials, polyval may be worth a look as well.
EDIT: After clarification, the problem seems a bit simpler, no need for function handles. Why not simply
function c = cost(p)
c = 0;
cf = [...]; % your coefficients here.
for k = 1 : size(cf, 1)
    c = c + cf(k,1) + cf(k,2)*p(k) + cf(k,3)*p(k)^2;
end


text:
Q: IBM TWS Java API queryFilter How to find job stream using job name? When I use this code:
                QueryFilter queryFilter = new QueryFilter();
                queryFilter.setFilter(JobStreamFilters.JOB_NAME, "JOBNAME");

                QueryResult queryResult = model.queryTWSObject(JobStream.class, queryFilter, 25, null);
                QueryContext queryContext = queryResult.getQueryContext();

I get the list of all applications from AD. How to get only this application where job is residing?

A: The JobStreamFilters.JOB_NAME is applicable only to IBM Workload Scheduler distributed, as indicated in the javadoc:

The job name filter. String parameter. (This filter can be used only with a TWS Distributed engine.)

Try using JobStreamFilters.JOB_DEFINITION_TASK instead.


text:
Q: Loading json file using torchtext I'm working on the dailydialog dataset, which I've converted into a
JSON file which looks something like this:
[{"response": "You know that is tempting but is really not good for our fitness.", "message": "Say, Jim, how about going for a few beers after dinner?"}, {"response": "Do you really think so? I don't. It will just make us fat and act silly. Remember last time?", "message": "What do you mean? It will help us to relax."}, {"response": "I suggest a walk over to the gym where we can play singsong and meet some of our friends.", "message": "I guess you are right. But what shall we do? I don't feel like sitting at home."}, {"response": "Sounds great to me! If they are willing, we could ask them to go dancing with us.That is excellent exercise and fun, too.", "message": "That's a good idea. I hear Mary and Sally often go there to play pingpong.Perhaps we can make a foursome with them."}, {"response": "All right.", "message": "Please lie down over there."}]
So, each item has two keys - response and message.
This is my first time using PyTorch, so I was following a few online available resources. These are the relevant snippets of my code:
def tokenize_en(text):
    return [tok.text for tok in spacy_en.tokenizer(text)]

src = Field(tokenize = tokenize_en,
            init_token = '<sos>',
            eos_token = '<eos>',
            lower = True)

fields = {'response': ('r', src)}

train_data, test_data, validation_data = TabularDataset.splits(
                                        path = 'FilePath',
                                        train = 'trainset.json',
                                        test = 'testset.json',
                                        validation = 'validationset.json',
                                        format = 'json',
                                        fields = fields
)

Although no errors are raised, despite having many items in my JSON file, the train, test and validation datasets strangely have only 1 example each, as seen in this image:
Image Showing the length of train_data, test_data and validation_data
I'd be really grateful if someone could point out the error to me.
Edit: I found out that the whole file is being treated as a single text string due to lack of indents in the file. But if I indent the JSON file, the TabularDataset function throws a JSONDecodeError to me, suggesting it can no more decode the file. How can I get rid of this problem?

A: I think the code is alright, but the issue is with your JSON file. Can you try removing the square brackets("[]") at the beginning and the end of the file?
Probably that is the reason that Your Python file is reading it as one single object.


text:
Q: How to log all requests with unfiltered I'm using unfiltered to provide restful API, and have defined several intents. Now I have a new requirement, I have to log all the request url into a file, but I can't find a good solution for it.
I've read the document of unfiltered, not found something like "filter/interceptor" in SpringMVC. Is there any way to do it?

A: No idea about SpringMVC. However, if you want to log every request you can write a logging Intent
object RequestLogging {
  def apply[A, B](intent: Cycle.Intent[A, B]) =
    Cycle.Intent[A, B] {
      case req =>
        Cycle.Intent.complete(intent)(req) ~> new ResponseFunction[Any]() {
          override def apply[C <: Any](resp: HttpResponse[C]) = {
            println(s"${req.remoteAddr} ${new Date()} ${req.method} ${req.uri} ${resp.underlying.asInstanceOf[Response].getStatus}")
            resp
          }
        }
    }
}

And then use it by wrapping your current Intent like this:
val plan = new unfiltered.filter.Plan {
  def intent = RequestLogging {
    case GET(Path("/record/1")) => ...
  }
}


text:
Q: Whitespace in AJAX response I'm getting white space in my console log from my response with AJAX. The responds I need to get is:"[1,4,6,12]" instead I'm getting: "[1,4,6,12] ".
I've tried everything... Deleting every PHP close tag, using the trim function(in PHP and JS)...
My PHP code(part not all):
$errors = array();

if (empty($stringUsername)) {
    $errors[] = 0;
    $bolean = true;
}
if (strlen($stringUsername) < 3 || strlen($stringUsername) > 16) {
    $errors[] = 1;
    $bolean = true;
}
if (!ctype_alnum($stringUsername)) {
    $errors[] = 2;
    $bolean = true;
}

if (empty($stringPassword)) {
    $errors[] = 3;
    $bolean = true;
}
if (strlen($stringPassword) < 6 || strlen($stringPassword) > 16) {
    $errors[] = 4;
    $bolean = true;
}

if (empty($stringPassword2)) {
    $errors[] = 5;
    $bolean = true;
}
if ($stringPassword != $stringPassword2) {
    $errors[] = 6;
    $bolean = true;
}

if (empty($stringEmail)) {
    $errors[] = 7;
    $bolean = true;
}
if (!filter_var($stringEmail, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 8;
    $bolean = true;
}

if ($intMatchu != 0) {
    $errors[] = 9;
    $bolean = true;
}
if ($intMatchu != 0) {
    $errors[] = 10;
    $bolean = true;
}

if (empty($stringTerms)) {
    $errors[] = 11;
    $bolean = true;
}
if ($stringTerms == 'avok') {
    $errors[] = 12;
    $bolean = true;
}

if ($bolean == false) {
    $errors[] = 100;
}
echo json_encode($errors);

My JS/AJAX part(not all):
if (username.val() != '' && password.val() != '' && password2.val() != '' && email.val() != '' && terms.val != '') {
    var UrlToPass = 'action=aanmelden&username=' + username.val() + '&password=' + password.val() + '&password2=' + password2.val() + '&email=' + email.val() + '&av=' + terms.val();

    $.ajax({
        type: 'POST',
        data: UrlToPass,
        url: '/outgame/register.php',
        success: function (responseText) {
            if (responseText == 0) {
                $.notify('U hebt geen gebruikersnaam opgegeven!', 'error');
            } else if (responseText == 1) {
                $.notify('Uw gebruikersnaam moet meer dan 3 en minder dan 16 karakters bevatten!', 'error');
            } else if (responseText == 2) {
                $.notify('Uw gebruikersnaam bevat ongeldige tekens!', 'error');
            } else if (responseText == 3) {
                $.notify('U hebt geen wachtwoord opgegeven!', 'error');
            } else if (responseText == 4) {
                $.notify('Uw wachtwoord moet meer dan 6 en minder dan 16 karakters bevatten!', 'error');
            } else if (responseText == 5) {
                $.notify('U hebt geen tweede wachtwoord opgegeven!', 'error');
            } else if (responseText == 6) {
                $.notify('De wachtwoorden komen niet met elkaar overeen!', 'error');
            } else if (responseText == 7) {
                $.notify('U hebt geen mail adres opgegeven!', 'error');
            } else if (responseText == 8) {
                $.notify('Uw mail adres is niet geldig!', 'error');
            } else if (responseText == 9) {
                $.notify('Uw gebruikersnaam is al ingebruik!', 'error');
            } else if (responseText == 10) {
                $.notify('Er is al een account aagemaakt met dit email adres!', 'error');
            } else if (responseText == 11) {
                $.notify('U hebt onze AV niet geaccepteerd!', 'error');
            } else if (responseText == 12) {
                $.notify('Uw invoer voor onze AV is ongeldig!', 'error');
            } else if (responseText == 100) {
                $.notify('U bent succesvol geregistreerd', 'success');
            } else {
                alert('error!');
            }
            console.log(responseText);
        }

Thank you in advance! I'm sorry for my grammar or spelling mistakes, English isn't my mother tongue :-)

A: You're echoing a JSON Encoded Array, then attempting to compare it to integer values.  That's never going to work.  Response is a String when you use $.ajax so you need to parse it into a JSON Value via something like this:
$.parseJSON("[1,2,3,4] ")  // Returns [1, 2, 3, 4]

Once you have a valid Array in JavaScript you want to see if your error codes are in that array, something like this:
[1, 2, 3, 4].indexOf(3) // returns 2

While an error that was not present would look like this:
[1, 2, 3, 4].indexOf(5) // returns -1


text:
Q: D3.JS, How can I render multiple objects in the same data binding? I have a data model which is an array of object with start time and end time.
Now I want to render gantt chart type cart with it.
It is easy to bind data and render a single line with it:
chart.data(myDataList).enter().append("line")
                              .attr("x1", function(d){return d.x})
                              .attr("y1", lineHeight)
                              .attr("x2", function(d){return d.y})
                              .attr("y2", lineHeight)

The data could be like
myDataList = [ [start time, end time],
               [start time 2, end time 2],
               [start time 3, end time 3]]

Now I need to render something like this with each data item:
O-------------------O
That is addition to the line, there will be circle in both end of the line.
Circle cx data will be coming from d.x and d.y.
However, I am not quite sure how to bind the same data element in three elements.
Any help?

A: First you make the line:
chart.data(myDataList).enter().append("line")
                              .attr("x1", function(d){return d.x})
                              .attr("y1", lineHeight)
                              .attr("x2", function(d){return d.y})
                              .attr("y2", lineHeight)

now make circles
//make inner circle
chart.selectAll(".in").data(dataset).enter()
  .append("circle")
   .attr("class", "in")
  .attr("cx", function(d) {
    return xScale(d[0])
  })
  .attr("cy", function(d) {
    return xScale(d[0])
  })
  .attr("r", 2);
  //make outer circle
  chart.selectAll(".out").data(dataset).enter()
  .append("circle")
  .attr("class", "out")
  .attr("cx", function(d) {
    return xScale(d[1])
  })
  .attr("cy", function(d) {
    return xScale(d[0])
  })
  .attr("r", 2);

Working code here

A: First,cache the line code in a variable.
 var line=chart.data(myDataList).enter().append("line")
.attr("x1", function(d){return d.x})
.attr("y1", lineHeight)
.attr("x2", function(d){return d.y})
.attr("y2", lineHeight)

Then,now using the variable,we can add circles using the same data element as
line.append("circle")
.attr("cx", function(d){return d.x})
.attr("cy", lineHeight)
.attr("r", 4);//First circle

now,the second circle ...
line.append("circle")
.attr("cx", function(d){return d.y})
.attr("cy", lineHeight)
.attr("r", 4);//Second circle


text:
Q: How to calculate $\sum_{x \in \mathbb{Z}^2} \frac{2\pi(1 - 2x_1)}{|2\pi x + \hat{\pi}|^4}$? Consider the series
$$\sum_{x=-\infty}^\infty \frac{2\pi(1 - 2x)}{(2\pi x + \pi)^4}.$$
This series converges to $\frac{\pi}{12}$ as can be seen in WolframAlpha . Now instead of a scalar $x$ I would like to consider instead a vector $x$ in $\mathbb{Z}^2$ and calculate the value of
$$\sum_{x \in \mathbb{Z}^2} \frac{2\pi(1 - 2x_1)}{|2\pi x + \hat{\pi}|^4},$$
where $\hat{\pi} = [\pi, \pi]^T$. So this could be viewed as a generalization of the previous summation to two dimensions.
How can the value that this series converges to be calculated?

A: Pulling out the $\pi$ factor,
$$ -\frac{2}{\pi^3}\sum_{x\in\mathbb{Z}}\frac{(2x-1)}{(2x+1)^4}=-\frac{2}{\pi^3}\sum_{n\geq 0}\left(\frac{(2n-1)}{(2n+1)^4}+\frac{-3-2n}{(2n+1)^4} \right)$$
equals
$$ \frac{8}{\pi^3}\sum_{n\geq 0}\frac{1}{(2n+1)^4} =\frac{8}{\pi^3}\left(\zeta(4)-\frac{1}{16}\zeta(4)\right)=\frac{8}{\pi^3}\cdot\frac{15}{16}\cdot\frac{\pi^4}{90}=\frac{\pi}{12}.$$
In a similar way, the second series equals
$$ \frac{16}{\pi^3}\sum_{x\geq 0}\sum_{y\geq 0}\frac{1}{\left((2x+1)^2+(2y+1)^2\right)^2}$$
that is deeply related with a Dirichlet series. It is:
$$ \frac{16}{\pi^3}\cdot\!\!\!\!\!\!\!\!\sum_{\substack{n\geq 1 \\ n\equiv 2\!\pmod{\!\!4}}}\!\!\!\!\!\! \frac{r_2(n)}{n^2}$$
where $r_2(n)$ stands for the number of ways for writing $n$ as a sum of two squares. Its explicit value is given by:
$$ \frac{7\sinh(\pi)\,\zeta(3)-\pi^3}{4 \pi ^2 (1+\cosh\pi)}. $$
That can be achieved through the Poisson summation formula.


text:
Q: Modify a file to remove repeated occurances using scripts input
# FILE:app/src/file1.c, something_over_here
something_over_here
# FILE:app/src/file1.c, something_over_here
something_over_here
# FILE:app/src/file2.c, something_over_here
something_over_here
# FILE:app/src/file2.c, something_over_here
something_over_here
...........

output
# FILE:app/src/file1.c, something_over_here
something_over_here
# FILE:app/src/file2.c, something_over_here
something_over_here
..........

I have an input file which consists of repeated occurrences of lines having same filename. I need to delete all except the first occurrence of each filename. How do I proceed? I am not very familiar with scripts(python/shell). I need to know which direction to proceed in.

A: Making many assumptions about what you actually want, try:
awk '/^#/ {p=H[$2]++} !p ' input > output

This simply scans the file and increments a counter when it sees a line beginning with a '#'.  The counter is kept for each filename (column 2 in the line beginning with a comment), and a line does not print if the counter for the most recently seen file has been seen before.


text:
Q: Why can't I pass wn.ADJ_SAT as a pos when requesting synsets I know that wordnet has an "adverb synset" type. I know that is in the synset type enum in nltk
from nltk.corpus import wordnet as wn
wn.ADJ_SAT
u's'

Why can't I pass it as a key to synsets?
>>> wn.synsets('dog', wn.ADJ_SAT)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/nltk/corpus/reader/wordnet.py", line 1413, in synsets
    for form in self._morphy(lemma, p)
  File "/Library/Python/2.7/site-packages/nltk/corpus/reader/wordnet.py", line 1627, in _morphy
    substitutions = self.MORPHOLOGICAL_SUBSTITUTIONS[pos]
KeyError: u's'

A: From:
>>> from nltk.corpus import wordnet as wn
>>> wn.synsets('able')
[Synset('able.a.01'), Synset('able.s.02'), Synset('able.s.03'), Synset('able.s.04')]
>>> wn.synsets('able', pos=wn.ADJ)
[Synset('able.a.01'), Synset('able.s.02'), Synset('able.s.03'), Synset('able.s.04')]
>>> wn.synsets('able', pos=wn.ADJ_SAT)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/nltk/corpus/reader/wordnet.py", line 1413, in synsets
    for form in self._morphy(lemma, p)
  File "/usr/local/lib/python2.7/dist-packages/nltk/corpus/reader/wordnet.py", line 1627, in _morphy
    substitutions = self.MORPHOLOGICAL_SUBSTITUTIONS[pos]
KeyError: u's'

From https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/wordnet.py#L1397 , we see that when you try to retrieve a synset from the NLTK wordnet API, the POS restrictions appears in the return list comprehension that calls the self._morphy(lemma, p) function:
def synsets(self, lemma, pos=None, lang='en'):
    """Load all synsets with a given lemma and part of speech tag.
    If no pos is specified, all synsets for all parts of speech
    will be loaded.
    If lang is specified, all the synsets associated with the lemma name
    of that language will be returned.
    """
    lemma = lemma.lower()

    if lang == 'en':
        get_synset = self._synset_from_pos_and_offset
        index = self._lemma_pos_offset_map
        if pos is None:
            pos = POS_LIST
        return [get_synset(p, offset)
                for p in pos
                for form in self._morphy(lemma, p)
                for offset in index[form].get(p, [])]

If we look at the _morphy() function, from https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/wordnet.py#L1573.
 def _morphy(self, form, pos):
        # from jordanbg:
        # Given an original string x
        # 1. Apply rules once to the input to get y1, y2, y3, etc.
        # 2. Return all that are in the database
        # 3. If there are no matches, keep applying rules until you either
        #    find a match or you can't go any further

        exceptions = self._exception_map[pos]
        substitutions = self.MORPHOLOGICAL_SUBSTITUTIONS[pos]

        def apply_rules(forms):
            return [form[:-len(old)] + new
                    for form in forms
                    for old, new in substitutions
                    if form.endswith(old)]

        def filter_forms(forms):
            result = []
            seen = set()
            for form in forms:
                if form in self._lemma_pos_offset_map:
                    if pos in self._lemma_pos_offset_map[form]:
                        if form not in seen:
                            result.append(form)
                            seen.add(form)
            return result

        # 0. Check the exception lists
        if form in exceptions:
            return filter_forms([form] + exceptions[form])

        # 1. Apply rules once to the input to get y1, y2, y3, etc.
        forms = apply_rules([form])

        # 2. Return all that are in the database (and check the original too)
        results = filter_forms([form] + forms)
        if results:
            return results

        # 3. If there are no matches, keep applying rules until we find a match
        while forms:
            forms = apply_rules(forms)
            results = filter_forms(forms)
            if results:
                return results

        # Return an empty list if we can't find anything
        return []

We see that it retrieves some substitution rules from substitutions = self.MORPHOLOGICAL_SUBSTITUTIONS[pos] to perform some morphological reduction before it retrieves the Synsets that are stored in the "based"/"root" form. E.g.
>>> from nltk.corpus import wordnet as wn
>>> wn._morphy('dogs', 'n')
[u'dog']

And if we look at the MORPHOLOGICAL_SUBSTITUTIONS, we see that ADJ_SAT is missing, see https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/wordnet.py#L1609 :
MORPHOLOGICAL_SUBSTITUTIONS = {
    NOUN: [('s', ''), ('ses', 's'), ('ves', 'f'), ('xes', 'x'),
           ('zes', 'z'), ('ches', 'ch'), ('shes', 'sh'),
           ('men', 'man'), ('ies', 'y')],
    VERB: [('s', ''), ('ies', 'y'), ('es', 'e'), ('es', ''),
           ('ed', 'e'), ('ed', ''), ('ing', 'e'), ('ing', '')],
    ADJ: [('er', ''), ('est', ''), ('er', 'e'), ('est', 'e')],
    ADV: []}

Thus to prevent this from happening a simple fix to add this line after line 1609 of https://github.com/nltk/nltk/blob/develop/nltk/corpus/reader/wordnet.py#L1609:
MORPHOLOGICAL_SUBSTITUTIONS[ADJ_SAT] = MORPHOLOGICAL_SUBSTITUTIONS[ADJ]

For proof of concept:
>>> MORPHOLOGICAL_SUBSTITUTIONS = {
...     1: [('s', ''), ('ses', 's'), ('ves', 'f'), ('xes', 'x'),
...            ('zes', 'z'), ('ches', 'ch'), ('shes', 'sh'),
...            ('men', 'man'), ('ies', 'y')],
...     2: [('s', ''), ('ies', 'y'), ('es', 'e'), ('es', ''),
...            ('ed', 'e'), ('ed', ''), ('ing', 'e'), ('ing', '')],
...     3: [('er', ''), ('est', ''), ('er', 'e'), ('est', 'e')],
...     4: []}
>>>
>>> MORPHOLOGICAL_SUBSTITUTIONS[5] = MORPHOLOGICAL_SUBSTITUTIONS[3]
>>> MORPHOLOGICAL_SUBSTITUTIONS
{1: [('s', ''), ('ses', 's'), ('ves', 'f'), ('xes', 'x'), ('zes', 'z'), ('ches', 'ch'), ('shes', 'sh'), ('men', 'man'), ('ies', 'y')], 2: [('s', ''), ('ies', 'y'), ('es', 'e'), ('es', ''), ('ed', 'e'), ('ed', ''), ('ing', 'e'), ('ing', '')], 3: [('er', ''), ('est', ''), ('er', 'e'), ('est', 'e')], 4: [], 5: [('er', ''), ('est', ''), ('er', 'e'), ('est', 'e')]}

A: Thanks for the suggestion, adopted in https://github.com/nltk/nltk/commit/21fd0c538b0144c5f722e4f643c9ced1deb1f15e


text:
Q: JQuery/Javascript: Error Message not displayed on Form So basically I have a form where a user is allowed to create a group. An error message is supposed to be displayed if the user does something they are not supposed to for example they enter a group name that already exists. My code is shown below.
Any help would be appreciated.
Just a side note, any error message that is related to the field works fine. For example, if you don't enter anything into a required field, error message is displayed as it should on the form.

A: I'm not too familiar with that code that's creating the group form, but it seems that
%div{:id => "id___all__"}

may not be creating the field
$('#non_field_errors');

that you're trying to reference in
jQuery.each(errors, function(i, error) {
    if (field != '__all__') {
        $fieldId = $('#id_'+field);
    } else {
        $fieldId = $('#non_field_errors');
    }

    $fieldId.closest('.control-group').addClass('error');
    $fieldId.parent().append(
        $('<span class="error_span">').addClass('help-inline').append(error));
    })

Basically, it SEEMS to me, without being 100% familiar with all this, that you're trying to place the errors into
$('#non_field_errors');

when you should be putting it into
$('#id___all__');

So nothing's happening. Let me know if this points you in the right direction. The loop itself appears to be working fine.


text:
Q: How to handle 'Uncaught:exception' in cypress cucumber test I want to handle uncaught exceptions occurs while running cypress tests using cucumber.I have to apply the settings before all the feature tests in all modules. How can I handle that?
I tried  this way, cy.on function in cypress config, but it is showing error for me.
 async setupNodeEvents(on, config) {
      await addCucumberPreprocessorPlugin(on, config);

      on(
        'file:preprocessor',
        createBundler({
          plugins: [createEsbuildPlugin(config)],
        }),

      );

    cy.on('uncaught:exception', (err, runnable) => {

         return false
      })

      return config;
    },

A: I would suggest to use the code in a different place, either in cypress/support/e2e.js
// cypress/support/e2e.js
Cypress.on('uncaught:exception', (err, runnable) => {
  return false
})

or inside the step file
// cypress/e2e/step-definition-for-feature-x.ts
import { When, Then } from "@badeball/cypress-cucumber-preprocessor";

Cypress.on('uncaught:exception', (err, runnable) => {
  return false
})

When('tests while ignoring an uncaught exception', () => {
  ...


text:
Q: How I can make custom map annotation pins? I need to make different points on the map with animation.
I want them to look like this: pin, and after tapped:tapped pin
Pictures change depending on the place in the array.
And when they are clustered, I want to see just a circle with the number of points inside. And when you press on clustered circle the map approaches. clusterring
My code:
import SwiftUI

struct MapMap: View {
    var body: some View {
        ZStack {
            MapView()
                .ignoresSafeArea()
        }
    }
}

struct MapMap_Previews: PreviewProvider {
    static var previews: some View {
        MapMap()
    }
}

import SwiftUI
import MapKit
import Combine

struct MapView: UIViewRepresentable {

    @ObservedObject private var network = NetworkManager()
    @Environment(\.colorScheme) private var colorScheme

    @State private var region = LocationsViewModel().mapRegion

    class Coordinator: NSObject, MKMapViewDelegate {

        var parent: MapView

        init(_ parent: MapView) {
            self.parent = parent
        }

        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            return AnnotationView(annotation: annotation, reuseIdentifier: AnnotationView.ReuseID)
        }

    }

    func makeCoordinator() -> Coordinator {
        MapView.Coordinator(self)
    }

    func makeUIView(context: Context) -> MKMapView {

        let mapView = MKMapView(frame: .zero)

        mapView.delegate = context.coordinator

        mapView.setRegion(region, animated: false)
        mapView.mapType = .standard
        mapView.preferredConfiguration.elevationStyle = .realistic
        mapView.isPitchEnabled = true
        mapView.pointOfInterestFilter = MKPointOfInterestFilter.excludingAll

        DispatchQueue.main.async {

            for points in network.clubs {

                let annotation = MKPointAnnotation()
                annotation.coordinate = CLLocationCoordinate2D(latitude: Double(points.latitude)!, longitude: Double(points.longitude)!)
                mapView.addAnnotation(annotation)
            }
        }
        return mapView
    }

    func updateUIView(_ uiView: MKMapView, context: Context) {}

}

let clusterID = "clustering"

class AnnotationView: MKMarkerAnnotationView {

    static let ReuseID = "cultureAnnotation"

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        clusteringIdentifier = clusterID
        markerTintColor = .black
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func prepareForDisplay() {
        super.prepareForDisplay()
        displayPriority = .defaultLow
    }
}

I did everything with swiftUI but I can't do clustering there.
Or how I can make map annotation with custom parameters?
Please help me.


text:
Q: DirectoryNotFoundException when trying to save image to wwwroot using this question I came up with this code to save a file
[HttpPost]
public IActionResult Upload(string office, IFormFile file)
{
    if (file.Length > 0) {
        var filePath = Path.GetFullPath(Path.Combine(_environment.WebRootPath,
            _configuration["SydneyFloorplanPath"]));

        using (var fileStream = new FileStream(filePath, FileMode.Create)) {
            file.CopyTo(fileStream);
        }
    }
    return RedirectToAction("Index", new{office = office});
}

But I get a super annoying issue when instantiating FileStream:

An exception of type 'System.IO.DirectoryNotFoundException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Could not find a part of the path 'C:\images\Floorplan\sydney.pdf'.'

But That's not the path that I need. The Images folder sits in my project under wwwroot\images...
what is the point of WebRootPath if it doesn't actually give me a usable, relative path?
Note that _environment is an injected IHostingEnvironment
I also noticed that if I call
var two = _environment.WebRootPath;

the varaible contains the full path... "C:\\Users\\bassie\\source\\repos\\TFS\\DSSTools\\wwwroot"
But after calling Path.Combine, I suddenly have "C:\\images\\Floorplan\\sydney.pdf" ... why?
Edit:
_environment is a IHostingEnvironment, eg:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace AspNetCorePathMapping
{
    public class HomeController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public HomeController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public ActionResult Index()
        {
            string webRootPath = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;

            return Content(webRootPath + "\n" + contentRootPath);
        }
    }
}

A: I managed to get this working with
[HttpPost]
public IActionResult Upload(string office, IFormFile file)
{
    var webRootPath  = _environment.WebRootPath;
    var floorPlanPath =  _configuration["SydneyFloorplanPath"];

    if (file.Length > 0) {
        var filePath1 = Path.Combine(floorPlanPath,webRootPath.ReplaceFirst("/", ""));

        using (var fileStream = new FileStream(filePath1, FileMode.Create)) {
            file.CopyTo(fileStream);
        }
    }
    return RedirectToAction("Index", new{office = office});
}

Where ReplaceFirst is a simple StringExtension
public static string ReplaceFirst(this string text, string search, string replace)
{
    int pos = text.IndexOf(search);
    if (pos < 0)
    {
        return text;
    }
    return $"{text.Substring(0, pos)}{replace}{text.Substring(pos + search.Length)}";
}

So it seems the leading / in webRootPath was breaking my Path.Combine call


text:
Q: Flag variable with user input to quit I have a program that is supposed to simulate a game of poker in java. I have a method class called Poker and a check class called CheckPoker which calls the methods in the method class. I haven't even been able to check if the algorithmic part works because while asking if the user would like to switch out any cards. The loop should quit after 5 cards have been entered or if the user enters "1" but in running the program, the for loop doesn't quit until 5 card values have been entered and then throws a "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 56" error. I have tried a for loop, a while loop, a do-while loop, but none have seemed to work thus far.
import java.util.*;

public class Poker {
    private String[] deck = {
            "D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA",
            "C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ", "CQ","CK","CA",
            "H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ", "HQ","HK","HA",
            "S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ", "SQ","SK","SA"};
    private List<String> hand = new ArrayList<>();
    public Poker(){
        Collections.shuffle(Arrays.asList(deck));
    }

    public void playGame(){
        System.out.print("The first five cards are: ");
        for(int i = 0; i<5; i++){
            System.out.print(deck[i] +", ");
        }
        System.out.println(" ");
        int k = 0;
        String j;
        List<String> discard = new ArrayList<>();
        Scanner in = new Scanner(System.in);
        System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
        while (k<5) { //this is the loop I'm having trouble with
            j = in.next();
            if(!j.equals("1")){
                j = in.next();
                discard.add(j);
                k++;
            }else{
                break;
            }
        }
        List deckList = Arrays.asList(deck);
        String[] discard1 = discard.toArray(new String[0]);
        for(int l = 0; l<k; l++){
            int m = deckList.indexOf(discard1[l]);
            String n = deck[m];
            deck[m] = deck[l+5];
            deck[l+5] = n;
        }
        System.out.print("Your new hand is: ");
        for(int i = 0; i<5; i++){
            System.out.print(deck[i] +", ");
            hand.add(deck[i]);
        }
        System.out.println(" ");
    }

A: Try the code below. It seems you were grabbing two cards per iteration and not capturing them all in the ArrayList.
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
    j = in.nextLine();
    if(j.equals("1") {
        break;
    }
    discard.add(j);
    k++;
}


text:
Q: SQL: Combine first two lines of a text field For each record in our MS SQL Server database, there is a text field. We would like to combine the first two lines of this text field. I have tried researching on this site and on Microsoft technet, and I do not know the proper way to write this in SQL. But, I believe the logic would be as follows:

copy text until char(13) from original column to new column
in new column, replace char(13) with nothing
remove text until char(13) from original column
concatenate text in new column with " | "
join old column to the right of new column

How would I write this as a query? Thank you. Database type: MS SQL Server 2008 R2

A: In your select statement you want to:

*

*Check the charindex of the char(13) of the text column, and

*make substring of that column once you know where the char(13) is.
Use those two functions and you'll get what you want =)
Example:
select SUBSTRING ( [YourTextColumn] ,0, CHARINDEX (char(13), [YourTextColumn] , 0 ) )
from YourTable

That will give you the first line of the column. You can check for the second line as well, just change the starting position of the charindex function.

A: SELECT  REPLACE(SUBSTRING(ColumnName, 0,
                          CHARINDEX(CHAR(13), ColumnName,
                                    CHARINDEX(CHAR(13), ColumnName, 0) + 1)),
                CHAR(13), '')
FROM    TableName


text:
Q: cPanel how to access the public_html via filezilla I have a big problem with cPanel. I have the access to cPanel but how ever I try to connect to public_html directory it is just impossible. I come so far that I enter the correct server but my uname and pword does not work. So please can someone tell me what I'm doing wrong?
I use Mac by the way.
If it helps I can say that I have installed mantis via simple script but I can't access that either via the url.
So I'm totally lost and please help me.

A: In your cpanel account, have you looked to see if you have an FTP account configured? Try using ftp.domain.com, cpanel username, cpanel password for FileZilla login credentials. Hope this helps.


text:
Q: Mysql GROUP and SUM Optimization I have 2 tables:
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `categoryId` int(10) unsigned DEFAULT NULL,
  `parentId` int(10) unsigned DEFAULT NULL,
  `barcode` varchar(255) DEFAULT NULL,
  `code` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_products_product_categories1_idx` (`categoryId`),
  KEY `fk_products_products1_idx` (`parentId`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=71521 ;

CREATE TABLE IF NOT EXISTS `inventory` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `depotId` int(10) unsigned NOT NULL,
  `productId` int(10) unsigned NOT NULL,
  `remain` int(11) DEFAULT NULL,
  `remain2` int(10) unsigned DEFAULT NULL,
  `updatedDateTime` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_inventory_depots1_idx` (`depotId`),
  KEY `fk_inventory_products1_idx` (`productId`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=89291 ;

Please help me to optimize the following query (what index should be added to improve the performance), Query took 0.2578 sec (MySQL is using index  fk_inventory_depots1_idx), when removing AND i.depotId = 3 Query took 0.5484 sec. EXPLAIN query show that Extra: Using where; Using temporary; Using filesort
SELECT `p`.* , SUM(i.remain) AS `remain` , SUM(i.remain2) AS `remain2`
FROM `products` AS `p`
LEFT JOIN `inventory` AS `i` ON p.id = i.productId
WHERE remain != 0 AND i.depotId = 3
GROUP BY `p`.`id`
ORDER BY `p`.`id` DESC
LIMIT 50

A: The sum() function used in your statement, would consider all the rows (the LIMIT clause would not be valid as its calculated at the last). The could be causing a full table scan as all the values of remain, remain2 are summed up
If you wish to get the sum() of the latest 50 rows use
SELECT
  `p`.* ,
  SUM(i.remain) AS `remain`,
  SUM(i.remain2) AS `remain2`
FROM
  (
    SELECT `p`.*,
          i.remain,
          i.remain2
    FROM
      `products` AS `p`
      JOIN `inventory` AS `i` ON p.id = i.productId << This should be a JOIN, as remain and depotId belong to inventory
    WHERE
      remain != 0
      AND i.depotId = 3
    GROUP BY
      `p`.`id`
    ORDER BY
      `p`.`id` DESC
LIMIT 50  ) as t

A: Your query looks ok, however, you have it as a LEFT-JOIN, but by using WHERE remain !=0 and i.DepotID = 3 forces it into an INNER-JOIN.  If you really intended for only entries that HAD non-zero remaining quantities, then you are ok.  But, if you want inventory products regardless, you would have to adjust your query to
SELECT
      `p`.* ,
      SUM(i.remain) AS `remain` ,
      SUM(i.remain2) AS `remain2`
   FROM `
      products` AS `p`
         LEFT JOIN `inventory` AS `i`
            ON p.id = i.productId
           AND remain != 0
           AND i.depotId = 3
   GROUP BY
      `p`.`id`
   ORDER BY
      `p`.`id` DESC
   LIMIT 50

Notice the subtle difference in the "ON" join condition.  This allows all products -- regardless of a matching inventory record.  Now, that said, you are now getting from ALL inventory, not just those of your "DepotID = 3" criteria.
To help your indexing, the only thing I would suggest is a multiple field key.  In this case, you are using most fields in the table for either the JOIN or SUM() purposes.  If the fields are part of the index, it doesn't have to go back to the actual data pages per record.  Small waste, but might get your final results improved.
KEY fk_inventory_multiplefields_idx ( productid, depotid, remain, remain2),


text:
Q: UUID shortening I need to calculate the daily number of unique users of an app.
The only way I can uniquely identify a user is via their UUID (this is externally supplied so I am forced to use it).
I know that my daily user counts are a couple of million users.
I'd like to use a bitset in Redis to do a population count, but in order for this to work, I'd need a way of narrowing my UUID so that it could comfortably fit into a long. I am aware of the potential for collisions but I am not concerned about precise numbers.
Has anyone done this in Java before? What I am after is how I could convert my UUID into something that could fit into a long.

A: There are two methods on the UUID object which might benefit you.
getLeastSignificantBits() and getMostSignificateBits(). Both return a long. Take one of these longs as your answer (or some kind of combination if you care.)

A: you could generate a hash of your uuids that generates ints or longs and use those for your population count.
have a look a `redis.clients.util.MurmurHash' in the jedis redis library. you can find it at https://github.com/xetorthio/jedis
*edit: sample
        UUID uuid = UUID.randomUUID();
        ByteBuffer buf = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits());
        buf.flip();
        int useMe= MurmurHash.hash(buf, 123);

A: This is probably small enough to fit directly using the full UUID as a hash key.  Approximations can also be made using less memory if that suites your needs.


text:
Q: Android - how to parse json with object at index I'm beginner, so I don't know how to parse json, when the json data doesn't have a key
This is my Json data
[
            {
                "products_id":10052,
                "products_name":"\u0e08\u0e35\u0e19 : The Haven Sword and Dragon Sabre - \u0e01\u0e23\u0e30\u0e1a\u0e35\u0e48\u0e1f\u0e49\u0e32\u0e14\u0e32\u0e1a\u0e21\u0e31\u0e07\u0e01\u0e23 1994 **\u0e1a\u0e32\u0e07\u0e15\u0e2d\u0e19\u0e2d\u0e32\u0e08\u0e44\u0e21\u0e48\u0e15\u0e48\u0e2d\u0e40\u0e19\u0e37\u0e48\u0e2d\u0e07\u0e15\u0e49\u0e2d\u0e07\u0e02\u0e2d\u0e2d\u0e20\u0e31\u0e22**",
                "products_description":"
\u0e19\u0e31\u0e01\u0e41\u0e2a\u0e14\u0e07:
- \u0e2b\u0e21\u0e48\u0e32\u0e08\u0e34\u0e48\u0e07\u0e40\u0e17\u0e32 (Steven Ma Jing Tao) \u0e23\u0e31\u0e1a\u0e1a\u0e17 \u0e40\u0e15\u0e35\u0e22\u0e1a\u0e48\u0e2d\u0e01\u0e35\u0e49 \u0e01\u0e31\u0e1a...",
                "products_date_available":"0",
                "products_image":"100909-TheHavenSword.jpg",
                "addDate":"2010-10-24 09:59:58"
            },
            {
                "products_id":10117,
                "products_name":"Nogizaka Haruka no Himitsu - \u0e04\u0e27\u0e32\u0e21\u0e25\u0e31\u0e1a\u0e02\u0e2d\u0e07\u0e22\u0e31\u0e22\u0e04\u0e38\u0e13\u0e2b\u0e19\u0e39 Season 1 + 2 (\u0e1a\u0e23\u0e23\u0e22\u0e32\u0e22\u0e44\u0e17\u0e22) **\u0e02\u0e2d\u0e2d\u0e20\u0e31\u0e22\u0e1a\u0e32\u0e07\u0e15\u0e2d\u0e19\u0e20\u0e32\u0e1e\u0e44\u0e21\u0e48\u0e15\u0e23\u0e07\u0e01\u0e31\u0e1a\u0e40\u0e2a\u0e35\u0e22\u0e07\u0e40\u0e19\u0e37\u0e48\u0e2d\u0e07\u0e08\u0e32\u0e01\u0e15\u0e49\u0e19\u0e09\u0e1a\u0e31\u0e1a**",
                "products_description":"
Nogizaka Haruka \u0e19\u0e32\u0e07\u0e40\u0e2d\u0e01\u0e02\u0e2d\u0e07\u0e40\u0e23\u0e37\u0e48\u0e2d\u0e07\u0e19\u0e35\u0e49 \u0e40\u0e1b\u0e47\u0e19\u0e44\u0e2d\u0e14\u0e2d\u0e25\u0e2b\u0e19\u0e36\u0e48\u0e07\u0e40\u0e14\u0e35\u0e22\u0e27\u0e02\u0e2d\u0e07\u0e42\u0e23\u0e07\u0e40\u0e23\u0e35\u0e22\u0e19\u0e19\u0e35...",
                "products_date_available":"0",
                "products_image":"10-NogizakaHarukaNoHimitsu.jpg",
                "addDate":"2010-09-30 10:20:03"
            }

I can't loop this Json because don't have a key for the method-call .getJSONArray("key")
This is my java
JSONObject object = new JSONObject(resultValue);

    //JSONArray jsonArray = object.getJSONArray("key");
    for (int i = 0; i < jsonArray.length(); i++){
     JSONObject objJson = jsonArray.getJSONObject(i);
     int products_id = objJson.getInt("products_id");
     String products_name = objJson.getString("products_name");
     Toast.makeText(getApplicationContext(),products_name,Toast.LENGTH_SHORT).show();

                    }

A: Your result contains a JSONArray with two indexes (0,1).
Run the loop twice or size of JSONArray. Get the value against the key products_id.
JSONArray array = new JSONArray(yourStringData);
for(int i = 0; i<array.length() ; i++){
   String productInfo = array.get(i);

   JSONObject object = new JSONObject(productInfo );
   String myRequiredData = object.get("products_id");
 }

A: You need to initialize JSONArray, instead of JSONObject:
JSONArray jsonArray = new JSONArray(resultValue); //resultValue is your string

after that, you can iterate through this array:
for (int i = 0; i < jsonArray.length(); i++){
 ...
}


text:
Q: Print out all files in a folder and its subfolders on a Mac I have a project with a lot of files under /app. There are also subfolders with files. How can I print(hard copy) these files all out without manually printing each one?
Note: Not the file names. I want to print(hard copy) the contents of all files under /app

A: Use find:
find /app

If you want print only directories, specify it with -type d (-type f to print files only):
find /app -type d

UPDATE
find /app -type f -print -exec cat {} \;

To get file hard copied, use lpr command:
find /app -type f -print -exec lpr {} \;


text:
Q: ACF Taxonomy images in product pages I'm struggling to populate ACF product_tag taxonomy images into product pages. Each product may be assigned to 1 or more product tag. I'd like to display those images and make the link to their archive pages.
ACF screenshot
Product Tag screenshot
I have this code but it is only showing the word "Tag". Can't make it pull the images:
add_action('woocommerce_before_add_to_cart_form','finish_image',22);
function finish_image() {
$terms = get_the_terms( $post->ID , 'product_tag' );
if($terms) {
foreach( $terms as $term ) {
$image = get_field('tag-image');
echo 'Tag ';
}
}
}

Anyone knows about this, please?
Regards!

A: Add term id as second parameter and use global $product, then try if you get image url
    add_action('woocommerce_before_add_to_cart_form','finish_image');
function finish_image() {
global $product;
$terms = get_the_terms( $product->get_id() , 'product_tag' );
if($terms) {
foreach( $terms as $term ) {
$image = get_field('tag-image', $term);
$url = get_term_link($term->term_id);
echo '';
}
}
}

A: For whoever needs it, here is the final code thanks to @DrashtiRajpura
add_action('woocommerce_before_add_to_cart_form','finish_image');
function finish_image() {
global $product;
$terms = get_the_terms( $product->get_id() , 'product_tag' );
if($terms) {
foreach( $terms as $term ) {
$image = get_field('tag-image', $term);
$url = get_term_link($term->term_id);
echo '';
}
}
}


text:
Q: How do I reconnect history when copying git projects? I have a Git project that was copied from another git project. It was just a file copy and commit, so it didn't copy history.  I've since imported the commits from the previous files, but they aren't connected to the new versions of the file. So if I look for the history of a file that exists in both repos, history only goes to the time I copied the project across.
I tried checking out the last revision of the old project, and git merging the first revision of the new project. Then I merged to master. This makes the project's git history look right, but each individual's file history is unchanged.
It's almost like we want to delete the revision that says "create all these files" and instead prepend the old project's history.
Is this possible with Git?

A:
prepend the old project's history. Is this possible with Git?

That should be possible, following this answer.
It uses git grafts described in git repository layout, but that old answer could benefit from the more recent git replace command.
See "Collating repositories or grafting earlier history with Git"

A: It seems to me that you can rebuild the history with a fairly straightforward cherry-pick:

*

*Given remotes old and new pointing to the old and new repos respectively

*Create a new branch from old/master, which is at the last revision of the old repo

*git cherry-pick first..new/master where first is the SHA1 of the first commit in the new repo (you can find it with git log new/master and press G to jump to the end)

The result will be basically the commits in the old repo + the commits in the new repo without first. As usual with a cherry-pick, commit dates and authors will be preserved.


text:
Q: MemoryError in the Nim Sum game on Leetcode I'm trying to solve the following problem from https://leetcode.com/problems/nim-game/description/:

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

I came up with the following solution, using a bottom-up dynamic programming approach:
class Solution(object):
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 3:
            return True
        win = [None for _ in range(n+1)]
        win[1] = win[2] = win[3] = True
        for n in range(4, n+1):
            win[n] = not all([win[n-i] for i in [1, 2 ,3]])
        return win[n]

However, when I try to submit this, I get a MemoryError:

Since the exact test case for which this MemoryError arises is not given, I'm struggling to see what is causing the problem. Any ideas?

A: Indeed as pointed out by Kenny Ostrom, probably the test cases are for such large n that there is insufficient memory to store the answers generated in the 'bottom up' dynamic programming approach. By running it on a smaller example, I noticed that the answer is simply
bool(x % 4)


text:
Q: Automating test cases with JBehave in an application in which UI is developed in SWING I want to automate some test cases in Jbehave in an application in which the UI is developed in SWING .
I don't want to do it with the UI (similar to Selenium) but want to call the functions of the UI(SWING) of the application .
Just want suggestions if I can use any other framework for the same or JBehave is a better option or if it is not feasible to use Jbehave for the same .
Thanks
Rahul


text:
Q: Java Headless browser with Flash Support I'm looking for a fast and reliable headless browser for Java that can interact with flash elements. I have already looked into PhantomJS, but there are too many errors when I try to run tests with PhantomJS on my target website. It also doesn't have flash support at all. If anyone knows of a headless browser that can interact with flash elements that would be great! Thanks!
Edit: So it appears that I need to state a problem and what I've done to try and solve it. The problem is that twitch.tv uses flash for many elements on their website, and when I try to run a headless browser such as HTMLUnit in Java or PhantomJS, they can't interact with those flash elements. I would like to know a workaround/solution for how I can continue using headless browsing but be able to interact with SWF elements.


text:
Q: Laravel CRUD, Edit and Delete ID Not Found, But ID Exist Here is migration.
Schema::create('ruanganjns', function (Blueprint $table) {
            $table->increments('id');
            $table->string('kode_jenis_ruangan');
            $table->string('jenis_ruangan');
            $table->date('tgl_berlaku');
            $table->string('status');
            $table->timestamps();
        });

Here is model.
protected $table = 'ruanganjns';
    protected $fillable = ['kode_jenis_ruangan','jenis_ruangan','tgl_berlaku','status'];
    public $timestamps = true;
    public function Ruangan()
    {
        return $this->HasMany('App\Ruangan','id_ruangan');
    }

here is controller edit code.
public function edit(Ruanganjns $ruanganjns)
    {
        $ruanganjns = Ruanganjns::findOrFail($ruanganjns->id);
        return view('ruanganjns.edit', compact('ruanganjns'));
    }

here is the route.
here
The main error always comes from an ID not found. even though all of my code is copied and pasted from the first code source, but the first source code all goes well. and the third source code and so on goes well. the source of the problem is always in this second table even i change it name or make it from beginning it's always the same. are there misspellings or case sensitive or something wrong with my code?
this is the result in the web browser
here

A: Your are trying to implement Implicit model binding but you have some wrong variable name in controller action. It should match with the route placeholder like this
Your route is like this
Route::get('admin/ruangjns/{ruangjn}/edit', 'RuanganjnsController@edit');

Then your controller action code should be like this
public function edit(Ruanganjns $ruangjn)  //here $ruangjn should match with route placeholder
{
    return view('ruanganjns.edit', compact('ruangjn'));
}

It automatically fetch model record and if record not found then it will return 404 error. For details check the above link


text:
Q: How do I get EOT to work on IF ELSE statement in bash? I'm trying to make a script that enables proxy settings if the /etc/environment file is currently empty and disables the settings if the file has text. I've written some code but not sure why the /etc/environment file is not being edited. I have blanked out the actual proxies I am using.
Any help would be greatly appreciated!
#!/bin/bash

        if [ -s /etc/environment ]
        then
            cat<<EOT >> /etc/environment
            http_proxy="blank"
            https_proxy="blank"
            ftp_proxy="blank"
            export http_proxy https_proxy ftp_proxy
            EOT
        else
            > /etc/environment
        fi

A: Use <<- instead of << if you want to indent the end token EOT or move EOT to first column.
Please take a look: http://www.shellcheck.net/

A: You can also move the here document to the if statement itself.
if [ -s /etc/environment ]; then
  cat
fi <<EOT >> /etc/environment
http_proxy="blank"
https_proxy="blank"
ftp_proxy="blank"
export http_proxy https_proxy ftp_proxy
EOT

although if the if statement itself is indented, you'll still want to know how to indent the here document as Cyrus explains.


text:
Q: Pandas - Merge of Dataframe with a Series Values I have a Dataframe (doc2) which basically looks like:
  Index     AgeGroups     Factor Cancer
    0        0_5  wo-statin    Yes
    1       6_10  wo-statin    Yes
    2      11_15  wo-statin    Yes
    3      16_20  wo-statin    Yes
    4      21_25  wo-statin    Yes
    5      26_30  wo-statin    Yes
    6      31_35  wo-statin    Yes
    7      36_40  wo-statin    Yes
    8      41_45  wo-statin    Yes
    9      46_50  wo-statin    Yes
    10     51_55  wo-statin    Yes
    11     56_60  wo-statin    Yes
    12     61_65  wo-statin    Yes
    13     66_70  wo-statin    Yes
    14     71_75  wo-statin    Yes
    15     76_80  wo-statin    Yes
    16     81_85  wo-statin    Yes
    17     86_90  wo-statin    Yes
    18     91_95  wo-statin    Yes
    19    96_100  wo-statin    Yes

And a Series (frame_concat) :
Index         0
0_5           0
6_10          0
11_15         0
16_20         2
21_25         1
26_30         4
31_35         1
36_40         2
41_45         4
46_50         5
51_55         5
56_60         2
61_65         3
66_70         3
71_75         2
76_80         0
81_85         0
86_90         0
91_95         0
96_100        0

Now, basically I want to merge both (doc2 , frame_concat) in such a way that (AgeGroups from doc2 = index from frame_concat) And Perhaps a new Column lets call it Frequency which contains values
0
0
0
0
2
1
4
1
2
4
5
5
2
3
3
2
0
0
0
0
0

Expecting to get a result as a whole like this :
Index     AgeGroups     Factor Cancer   Frequency
        0        0_5  wo-statin    Yes    0
        1       6_10  wo-statin    Yes    0
        2      11_15  wo-statin    Yes    0
        3      16_20  wo-statin    Yes    2
        4      21_25  wo-statin    Yes    1
        5      26_30  wo-statin    Yes    4
        6      31_35  wo-statin    Yes    1
        7      36_40  wo-statin    Yes    2
        8      41_45  wo-statin    Yes    4
        9      46_50  wo-statin    Yes    5
        10     51_55  wo-statin    Yes    5
        11     56_60  wo-statin    Yes    2
        12     61_65  wo-statin    Yes    3
        13     66_70  wo-statin    Yes    3
        14     71_75  wo-statin    Yes    2
        15     76_80  wo-statin    Yes    0
        16     81_85  wo-statin    Yes    0
        17     86_90  wo-statin    Yes    0
        18     91_95  wo-statin    Yes    0
        19    96_100  wo-statin    Yes    0

I am thankful for any help provided :) . Thank you so much

A: Try this:
In [170]: doc2.merge(frame_concat.to_frame('Frequency'), left_on='AgeGroups',
                     right_index=True, how='left')
Out[170]:
      AgeGroups     Factor Cancer  Frequency
Index
0           0_5  wo-statin    Yes          0
1          6_10  wo-statin    Yes          0
2         11_15  wo-statin    Yes          0
3         16_20  wo-statin    Yes          2
4         21_25  wo-statin    Yes          1
5         26_30  wo-statin    Yes          4
6         31_35  wo-statin    Yes          1
7         36_40  wo-statin    Yes          2
8         41_45  wo-statin    Yes          4
9         46_50  wo-statin    Yes          5
10        51_55  wo-statin    Yes          5
11        56_60  wo-statin    Yes          2
12        61_65  wo-statin    Yes          3
13        66_70  wo-statin    Yes          3
14        71_75  wo-statin    Yes          2
15        76_80  wo-statin    Yes          0
16        81_85  wo-statin    Yes          0
17        86_90  wo-statin    Yes          0
18        91_95  wo-statin    Yes          0
19       96_100  wo-statin    Yes          0

A: what about simple?
doc2['Frequency'] = frame_concat


text:
Q: On Mac OSX how can I associate a script file with Terminal so double clicking the icon launches Terminal? I have a python script that I can run in the usual way using Terminal. For example, launch Terminal, cd to the directory, then type ./xxx.py where xxx.py is the name of the file that contains the script.
Now I want to make an icon on the desktop that launches Terminal and runs the python file when I double click it. How do I do that? I thought I could make a shell file with the cd and the launch command and then associate that shell file with Terminal. But I can't seem to associate it with Terminal.
Somebody said to name the shell file with the suffix '.command' but that causes it to launch Flash Builder. I don't know where that associate is set. I can't manually associate Terminal because I can't find it. It isn't in /Applications.

A: On your Desktop you coul create a file with the following content
#!/bin/bash

python PATH_TO_YOUR_PYTHON_FILE

Then you must make it executable via
chmod u+x FILE_ON_DESKTOP

Alternatively you can create a symbolic link to your python file and make it executable.
You can find Terminal in /Applications/Utilities


text:
Q: How do I handle null equality in a generic context? I'm writing a generic method and I want to test a generic var for null. The operator == cannot be used since the compiler doesn't know if whether it's a value or reference type. So I used Equals
public void MyGenericMethod<T>(T myGenericVar)
{
    bool isNull = myGenericVar.Equals(default(T));
    [...]
}

It happens that if T is a reference type, default(T) is actually null and calling Equals on null produces a NullReferenceException.
How do I handle null equality in a generic way?


text:
Q: Trailing zeros vs rounding in siunitx I want to typeset U=220kV and C=12,8nF. This is my MWE:
\documentclass[ngerman]{scrartcl}
\usepackage[locale = DE]{siunitx}
\sisetup{
  exponent-mode = engineering,
  prefix-mode = combine-exponent
}
\begin{document}
 $U=\qty{220000}{\V}$ ,
 $C=\qty{0,0000000128}{\F}$
\end{document}

This is the result:

C=12,8nF is fine, but U=220,000kV has unwanted trailing zeros. Addition of siunitx-option round-pad=false has no effect on these zeros.
Similar with additional option round-mode = places, only the amount of trailing zeros depends on the choice of round-precision.
Use of round-mode = figures instead yields:
Now U=220kV is fine, but C has unwantedly been rounded to C=13nF. Because of a default round-precision=2 ?
After a further addition of the option round-precision=3 finally everything is fine. But only in this example.
I don't know the amount of significant figures or places in advance, so I would prefer a more general mechanism to avoid both unwanted trailing zeros or unwanted rounding. How could this work?


text:
Q: OpenCV mass center point I found the mass center of an irregular shape, but now I need to compute the distance to any given point.
I understand that the mc is a vector of points, but how can I find the coordinates of mc so I can calculate the distance between the mass center and some other point.Thanks
vector<Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{
    mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 );
}

A: First you should get the point by index. Let :
int size = contours.size();

The indices are: i = 0 ... size . The point at index i is
mc[i];

The coordinates of that point can be reached by:
float xCoor = mc[i].x;
float yCoor = mc[i].y;

Of course you can read those values in a loop from i = 0 to size if you want to read all the coordinates of all the mc points.
Edit:
I assumed that you knew how to find the mass center, and was just asking how to get the coordinates. But if you want to get mass center and the distance from mass center to some other point then you could do the following:
float distance;
float totalX=0.0, totalY=0.0;
for(int i=0; i<size; i++) {
    totalX+=mc[i].x;
    totalY+=mc[i].y;
}

Point2f massCenter(totalX/size, totalY/size); // condition: size != 0
Point2F someOtherPoint(someXVal, someYVal);

distance = massCenter.distance(someOtherPoint);

is the distance from mass center to some other point.
Hope that helps!

A: mc[i].x and mc[i].y are the x and y coordinates of the point of index i.
To compute the center of mass:
cv::Point2f baricenter(0,0);
for( int i = 0; i < mc.size(); i++ )
    barycenter += mc[i];
barycenter.x /= mc.size();
barycenter.y /= mc.size();

Check that you have at least one point in your vector.


text: Q: deploy report with subreport using jrs-rest-java-client API I am using JasperReports Server with its jrs-rest-java-client API. When I access the remote server I want to inject sub reports  that the report should use. how can i do that?


text:
Q: Checking if an XML element is marked with `xsi:nil` in SQL I am working on a stored procedure which shreds an XML document. One of the child elements in the records being processed can sometimes be marked with the xsi:nil="true" attribute. Other times, it can contain a dateTime. I'm trying to insert a string into a column of my table which depends on whether or not this element has a value. For example:
[Status] = CASE WHEN (Rt.Item.value('(./Date)[1]', 'nvarchar(max)') = '') THEN N'SUBMITTED' ELSE N'PROCESSED' END

Unfortunately, this doesn't seem to be working. What's the correct to check if an element has a value in SQL Server?

A: Generally:
theElementName[not(@xsi:nil eq 'true')]/any/other/needed/location/steps

If the association of the "xsi" prefix to the appropriate namespace isn't registered (the way to do this is implementation-specific and you need to check how this is to be done in your situation), one still can use:
theElementName[not(@*[name() eq 'xsi:nil'] eq 'true')]


text:
Q: REST API - Endpoint syntax - get item by property - not by id I'm implementing my first REST API, and I have a question about the syntax of the URL endpoints.
I know that I should use these endpoint for get, create, update and delete:

*

*Get list of items
Method: GET, Url: /api/items

*Get item by id
Method: GET, Url: /api/items/:id

*Add item (new item data in the request body)
Method: POST, Url: /api/items

*Modify item (modified item data in the request body)
Method: PUT, Url: /api/items/:id

*Delete item
Method: DELETE, Url: /api/items/:id
But lets say the interface of item is
interface item
{
  id: string;
  name: string;
}

What should be the request url for getting an item by it's name?
I can't use Method: GET, Url: /api/items/:name, because this will match the get-by-id request. So how should I syntax this endpoint?

A: There is no standard REST URI syntax unless you are doing OData for example. You have perfect freedom designing your own URIs, even /resource/{id} is perfectly valid.
What I like to do is end the URIs of collections with / and use queries for filtering collections. So I would do /api/{version}/items/?name={name} if they have unique names and you expect an item instead of a collection, then I would do it this way: /api/{version}/items/name:{name}. But this is my style.
From client perspective the URI syntax is totally irrelevant, because the server gives the valid URI templates to the client according to the HATEOES constraint. If you thought otherwise, then probably you are building a CRUD API instead of a REST API.

A: You chould use a filter on the collections endpoint like:
Method: GET, Url: /api/items?name=foo
This filter could return all items which have a foo string in them (depending on how you want to handle wildcards in the search / filter term), e.g. the response could be a collection of items:
{
    "data": [
        {
            "id": "d079d8e9-4d24-4514-b356-78587f6c2ba9",
            "name": "foo"
        },
        {
            "id": "7f5e558c-6a7f-4ebe-8f4f-a2d029a803ed",
            "name": "foo bar"
        }
    ]
}

If you want the response to return a single resource you could also use the name as identifier and apply the scheme from above using the name, e.g.
Method: GET, Url: /api/items/:name