text:
Q: ReactNative:Failed to parse React Native CLI configuration: groovy.json.JsonException: Unable to determine the current character started a new react-native project, followed link react native cli quickstart approach. even though I have not done any code change , getting the below error when i run npx react-native run-android
Version info:
    "react": "16.9.0",
    "react-native": "0.61.5"

Error info:
:ReactNative:Failed to parse React Native CLI configuration: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object

The current character read is 'I' with an int value of 73
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0

FAILURE: Build failed with an exception.

* Where:
Script 'D:\xp\feb2020xp\AwesomeProject\node_modules\@react-native-community\cli-platform-android\native_modules.gradle' line: 200
* What went wrong:
A problem occurred evaluating script.
> Failed to parse React Native CLI configuration. Expected running 'npx.cmd --quiet --no-install react-native config' command from 'D:\xp\feb2020xp\AwesomeProject' directory to output valid JSON, but it didn't. This may be caused by npx resolving to a legacy global react-native binary. Please make sure to uninstall any global 'react-native' binaries: 'npm uninstall -g react-native react-native-cli' and try again

What I Tried :
npm uninstall -g react-native react-native-cli
and
npx.cmd --quiet --no-install react-native config
console ouput from 2nd command:
{
  "root": "D:\\xp\\feb2020xp\\AwesomeProject",
  "reactNativePath": "D:\\xp\\feb2020xp\\AwesomeProject\\node_modules\\react-native",
  "dependencies": {},
  "commands": [
    {
      "name": "log-ios",
      "description": "starts iOS device syslog tail"
    },
    {
      "name": "run-ios",
      "description": "builds your app and starts it on iOS simulator",
      "examples": [
        {
          "desc": "Run on a different simulator, e.g. iPhone 5",
          "cmd": "react-native run-ios --simulator \"iPhone 5\""
        },
        {
          "desc": "Pass a non-standard location of iOS directory",
          "cmd": "react-native run-ios --project-path \"./app/ios\""
        },
        {
          "desc": "Run on a connected device, e.g. Max's iPhone",
          "cmd": "react-native run-ios --device \"Max's iPhone\""
        },
        {
          "desc": "Run on the AppleTV simulator",
          "cmd": "react-native run-ios --simulator \"Apple TV\"  --scheme \"helloworld-tvOS\""
        }
      ],
      "options": [
        {
          "name": "--simulator [string]",
          "description": "Explicitly set simulator to use. Optionally include iOS version betweenparenthesis at the end to match an exact version: \"iPhone 6 (10.0)\"",
          "default": "iPhone 11"
        },
        {
          "name": "--configuration [string]",
          "description": "Explicitly set the scheme configuration to use",
          "default": "Debug"
        },
        {
          "name": "--scheme [string]",
          "description": "Explicitly set Xcode scheme to use"
        },
        {
          "name": "--project-path [string]",
          "description": "Path relative to project root where the Xcode project (.xcodeproj) lives.",
          "default": "ios"
        },
        {
          "name": "--device [string]",
          "description": "Explicitly set device to use by name.  The value is not required if you have a single device connected."
        },
        {
          "name": "--udid [string]",
          "description": "Explicitly set device to use by udid"
        },
        {
          "name": "--no-packager",
          "description": "Do not launch packager while building"
        },
        {
          "name": "--verbose",
          "description": "Do not use xcpretty even if installed"
        },
        {
          "name": "--port [number]",
          "default": 8081
        },
        {
          "name": "--terminal [string]",
          "description": "Launches the Metro Bundler in a new window using the specified terminal path."
        }
      ]
    },
    {
      "name": "log-android",
      "description": "starts logkitty"
    },
    {
      "name": "run-android",
      "description": "builds your app and starts it on a connected Android emulator or device",
      "options": [
        {
          "name": "--root [string]",
          "description": "Override the root directory for the android build (which contains the android directory)",
          "default": ""
        },
        {
          "name": "--variant [string]",
          "description": "Specify your app's build variant",
          "default": "debug"
        },
        {
          "name": "--appFolder [string]",
          "description": "Specify a different application folder name for the android source. If not, we assume is \"app\"",
          "default": "app"
        },
        {
          "name": "--appId [string]",
          "description": "Specify an applicationId to launch after build.",
          "default": ""
        },
        {
          "name": "--appIdSuffix [string]",
          "description": "Specify an applicationIdSuffix to launch after build.",
          "default": ""
        },
        {
          "name": "--main-activity [string]",
          "description": "Name of the activity to start",
          "default": "MainActivity"
        },
        {
          "name": "--deviceId [string]",
          "description": "builds your app and starts it on a specific device/simulator with the given device id (listed by running \"adb devices\" on the command line)."
        },
        {
          "name": "--no-packager",
          "description": "Do not launch packager while building"
        },
        {
          "name": "--port [number]",
          "default": 8081
        },
        {
          "name": "--terminal [string]",
          "description": "Launches the Metro Bundler in a new window using the specified terminal path."
        },
        {
          "name": "--tasks [list]",
          "description": "Run custom Gradle tasks. By default it's \"installDebug\""
        },
        {
          "name": "--no-jetifier",
          "description": "Do not run \"jetifier\" – the AndroidX transition tool. By default it runs before Gradle to ease working with libraries that don't support AndroidX yet. See more at: https://www.npmjs.com/package/jetifier.",
          "default": false
        }
      ]
    }
  ],
  "assets": [],
  "platforms": {
    "ios": {},
    "android": {}
  },
  "haste": {
    "providesModuleNodeModules": [
      "react-native"
    ],
    "platforms": [
      "ios",
      "android"
    ]
  },
  "project": {
    "ios": {
      "sourceDir": "D:\\xp\\feb2020xp\\AwesomeProject\\ios",
      "folder": "D:\\xp\\feb2020xp\\AwesomeProject",
      "pbxprojPath": "D:\\xp\\feb2020xp\\AwesomeProject\\ios\\AwesomeProject.xcodeproj\\project.pbxproj",
      "podfile": "D:\\xp\\feb2020xp\\AwesomeProject\\ios\\Podfile",
      "podspecPath": null,
      "projectPath": "D:\\xp\\feb2020xp\\AwesomeProject\\ios\\AwesomeProject.xcodeproj",
      "projectName": "AwesomeProject.xcodeproj",
      "libraryFolder": "Libraries",
      "sharedLibraries": [],
      "plist": [],
      "scriptPhases": []
    },
    "android": {
      "sourceDir": "D:\\xp\\feb2020xp\\AwesomeProject\\android\\app",
      "isFlat": false,
      "folder": "D:\\xp\\feb2020xp\\AwesomeProject",
      "stringsPath": "D:\\xp\\feb2020xp\\AwesomeProject\\android\\app\\src\\main\\res\\values\\strings.xml",
      "manifestPath": "D:\\xp\\feb2020xp\\AwesomeProject\\android\\app\\src\\main\\AndroidManifest.xml",
      "buildGradlePath": "D:\\xp\\feb2020xp\\AwesomeProject\\android\\app\\build.gradle",
      "settingsGradlePath": "D:\\xp\\feb2020xp\\AwesomeProject\\android\\settings.gradle",
      "assetsPath": "D:\\xp\\feb2020xp\\AwesomeProject\\android\\app\\src\\main\\assets",
      "mainFilePath": "D:\\xp\\feb2020xp\\AwesomeProject\\android\\app\\src\\main\\java\\com\\awesomeproject\\MainApplication.java",
      "packageName": "com.awesomeproject"
    }
  }
}

I am unable to figure out what is going wrong. please help me in resolving the error . thank you.

A: I experienced a similar issue. The problem for me turned out to be a syntax error in the file android/app/src/main/AndroidManifest.xml.
Specifically, I had a wrong part like android:screenOrientation=portrait rather than the correct android:screenOrientation="portrait" (note the quotation marks).
Although the specific reason for the problem likely does not match yours, it may hopefully give you a hint for a potential solution.


text:
Q: cassandra: does/can it return new version ID after insert or update? Pseudo code:
ok, id = cassandra.insert(object,....);
printf("version of inserted object %d\n", id);
ok, id = cassandra.update(object,....);
printf("version of updated object %d\n", id);
ok, id = cassandra.update(object,....);
printf("version of updated object %d\n", id);

This is might print:
version of inserted object 1
version of updated object 2
version of updated object 3
Any monotonically increasing datum will work.

A: No, it can't - it's very hard to do in the distributed system...
Records are versioned by their timestamp, that is set by client by default (in recent versions of drivers).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate values per time interval in r I have a data set with measurements every 5 minutes over 48 hours from different groups, each with several samples (about 32 samples in total).
I would like to calculate the mean value and the difference of each sample per hour for the measured values.
I have the times as datetime in POSIXct format "YYYY-MM-DD hh:mm:ss" and as hms (running_time) in format "hh:mm:ss".
The datetime always has different start times for each sample, the running_time always starts at 00:00:00 and was calculated from the datetime as follows:
group_by(sample)%>%mutate(running_time = `units<-`(date_time - date_time[1], "hours"))

So for each sample I have to calculate the mean value from the start time 00:00:00 to 01:00:00 or the difference between the start time and 01:00:00, then from 01:00:00 to 02:00:00 and so on for the entire 48 hours.
The original data is quite large: ~33000 observations of 46 variables. At the end I like to plot the mean/total change of measurements per hour.
I'm fairly new to r and would appreciate any help!
Little insight into the table (abbreviated):
# A tibble: 33,291 × 5
# Groups:   sample [63]
   date_time           running_time sample    ee  grams_feed
   <dttm>              <time>        <dbl> <dbl> <dbl>
 1 2022-07-02 05:59:00 00'00"         6906 0.447  10.9
 2 2022-07-02 06:04:00 05'00"         6906 0.509  10.9
 3 2022-07-02 06:09:00 10'00"         6906 0.484  11.0
 4 2022-07-02 06:14:00 15'00"         6906 0.425  11.0
 5 2022-07-02 06:19:00 20'00"         6906 0.366  11.0
 6 2022-07-02 06:24:00 25'00"         6906 0.318  11.0
 7 2022-07-02 06:29:00 30'00"         6906 0.26   11.0
 8 2022-07-02 06:34:00 35'00"         6906 0.283  11.0
 9 2022-07-02 06:39:00 40'00"         6906 0.283  11.0
10 2022-07-02 06:44:00 45'00"         6906 0.259  11.0
# … with 33,281 more rows

> dput(head(df))
structure(list(date_time = structure(c(1656741540, 1656741840,
1656742140, 1656742440, 1656742740, 1656743040), tzone = "UTC", class = c("POSIXct",
"POSIXt")), running_time = structure(c(0, 300, 600, 900, 1200,
1500), class = c("hms", "difftime"), units = "secs"), sample = c(6906,
6906, 6906, 6906, 6906, 6906), ee = c(0.447, 0.509, 0.484, 0.425,
0.366, 0.318), grams_feed = c(10.91, 10.92, 10.98, 10.98, 10.99,
10.99)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), groups = structure(list(sample = 6906,
    .rows = structure(list(1:6), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L), .drop = TRUE))

A: Something like:
df %>%
  mutate(time= lubridate::floor_date(date_time, unit = "hour")) %>%
  group_by(sample, time) %>%
  summarise(
      across(a:j, list(mean = mean, sum = sum, min = min, max = max))
  ) # this will summarize column a to j by mean, sum, min and max

Should do the work ?


text:
Q: Adding permissions to django users which have add-on models I will be creating an intranet site with multiple roles (client-employee, client-admin, staff team member). Each role will have a model that attaches (via One-to-One or ForeignKey field) to a user with custom fields. I want each role to have it's own set of permissions (like a group).
How can I store this permissions set inside my application. Groups seem to be defined as part of the contrib.admin app rather than in code. I couldn't find anything in documentation on how to define a group.
What is the best way to handle model level permissions. Maybe I could do a check in the model if see if the user has the right role-model.

A: Access control lists are tricky (some say dead), but Django comes with a good default implementation in contrib.auth equipped with:

*

*Users

*Permissions: Binary (yes/no) flags designating whether a user may perform a certain task.

*Groups: A generic way of applying labels and permissions to more than one user.

A more detailed introduction can be found here:

*

*http://parand.com/say/index.php/2010/02/19/django-using-the-permission-system/


text:
Q: Should I keep a database connection open to handle every request? And how to do that in the right way For example a database such as MongoDB. I doubt that it is unnecessary to open and close a connection for every request. So I try to keep a connection to handle every request like this.
public class MongoUtils {
private static final String connectionString = "mongodb://localhost:27017";
private static final MongoClient client;

static {
    client = MongoClients.create(connectionString);
}

public static MongoClient getConnection(){
    return client;
}

}

But maybe I'm doing this wrong somewhere. I don't know why it create the first connection and leave it there, then it create the second connection and use that to handle my db request. Here's the log
2018-10-25 11:37:36 INFO  AnnotationMBeanExporter:433 - Registering beans for JMX exposure on startup
2018-10-25 11:37:36 INFO  Http11NioProtocol:180 - Starting ProtocolHandler ["http-nio-8808"]
2018-10-25 11:37:36 INFO  NioSelectorPool:180 - Using a shared selector for servlet write/read
2018-10-25 11:37:36 INFO  TomcatWebServer:206 - Tomcat started on port(s): 8808 (http) with context path '/api'
2018-10-25 11:37:36 INFO  Backend:59 - Started Backend in 3.251 seconds (JVM running for 6.935)
2018-10-25 11:37:56 INFO  [/api]:180 - Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-10-25 11:37:56 INFO  DispatcherServlet:494 - FrameworkServlet 'dispatcherServlet': initialization started
2018-10-25 11:37:56 INFO  DispatcherServlet:509 - FrameworkServlet 'dispatcherServlet': initialization completed in 39 ms
2018-10-25 11:37:56 INFO  cluster:71 - Cluster created with settings {hosts=[10.184.153.232:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-10-25 11:37:56 INFO  cluster:71 - Cluster description not yet available. Waiting for 30000 ms before timing out
2018-10-25 11:37:56 INFO  connection:71 - Opened connection [connectionId{localValue:1, serverValue:27}] to 10.184.153.232:27017
2018-10-25 11:37:56 INFO  cluster:71 - Monitor thread successfully connected to server with description ServerDescription{address=10.184.153.232:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 3]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3393851}
2018-10-25 11:37:56 INFO  connection:71 - Opened connection [connectionId{localValue:2, serverValue:28}] to 10.184.153.232:27017

A: Look up "connection pooling" which is the idea of having a "pool" of connections left open that your requests can use. If they are idle a while you can program them to close; conversely if they are overloaded you can program a connection pool to open even more connections to accommodate the load. They are tunable / configurable in other ways.

*

*MongoDB Java Driver database connection pooling with Tomcat

*How to establish a connection pool in JDBC?

A: To quote directly from the JavaDocs of com.mongodb.MongoClient:

A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.

The client itself has internal connection pooling and is thread-safe. So you should use a single MongoClient instance for your application.
This suggests that you're already using it as recommended.


text:
Q: Insert character into SQL string I have an nvarchar column I need to insert a hyphen at fixed points within the string. The hyphen need to go between the rightmost character and the next, and again in the 3rd position from the right, such as:
column value is
0000050704

and I need it to be
0000050-70-4

or value is
0555256321

and it should be
0555256-32-1

Can't see how this is done. Can anyone give me a little help?

A: Assuming the strings can be a variable length, you'll need to use REVERSE() or lots of nasty looking LEN() values in your expression.
declare @txt varchar(100) = '0000050704'

--If using SQL Server, the STUFF() function is your friend
select REVERSE(STUFF(STUFF(REVERSE(@txt), 2, 0, '-'), 5, 0, '-'))

--if not you'll need to concatenate SUBSTRING()s
select REVERSE(SUBSTRING(REVERSE(@txt), 1, 1) + '-' + SUBSTRING(REVERSE(@txt),2, 2) + '-' + SUBSTRING(REVERSE(@txt),4, LEN(@txt)))

A: You  can use this easy function:
CREATE FUNCTION [dbo].[SetHyphen] (@S varchar(50)) RETURNS varchar(52)
BEGIN
RETURN STUFF(STUFF(@S,LEN(@S)-2,0,'-'),LEN(@S)+1,0,'-')
END

For example:
select [dbo].[SetHyphen]('0000050704')
0000050-70-4

A: It depends on your SQL server. Please check the documentation on how to manipulate strings - I will  suppose SUBSTRING function.
In MS SQL Server you can do sth. like this:
UPDATE YourTableName SET
    YourFieldName =
        SUBSTRING(YourFieldName, 1,7) + "-" +
        SUBSTRING(YourFieldName, 7,2) + "-" +
        SUBSTRING(YourFieldName, 9,1)

This will split your field content in three parts and rebuild it with separators...
Before running the query I will suggest you try it as plain SELECT to see if it works as needed:
SELECT
    SUBSTRING(YourFieldName, 1,7) + "-" +
    SUBSTRING(YourFieldName, 7,2) + "-" +
    SUBSTRING(YourFieldName, 9,1)
FROM YourTableName

Take care that the query is without WHERE condition and thus will affect ALL rows of your table.


text:
Q: Angular : send user activity to server I would like to send user activities to server, especially which button the user clicked.
What I would like to do is same with this post as I asked before. The post is AngularJS, what I would like to ask is Angular ( I am using Angular8 ).
I know I can do it like this.
HTML:
<button (click)="pressA()">A</buttion>
<button (click)="pressB()">B</buttion>

Typescript:
@Component({
  templateUrl:"my.html"
})
export class MyApp {

  pressA() {
    sendServer("A");
    // Do other things for button A
  }

  pressB() {
    sendServer("B");
    // Do other things for button B
  }

  sendServer(val: string) {
    // POST val to https://(mydomain)/(path)
  }
}

But this way require me to insert sendServer to all click event. It is bothersome. Can I do this more efficient way?

A: For your use-case, I'd recommend that you use a directive and for every button that you write in your templates. The code would be somewhat like this

<p>
  <button clickMonitor>1</button>
  <button clickMonitor>2</button>
  <button clickMonitor (clickEmitter) = "data($event)">3</button>
</p>

Here's this Angular demo how to achieve this
https://stackblitz.com/edit/angular-s5rjtp
Now, there's multiple scope of enhancements here, like you can add a debounce effect on the clicks, so that you don't end up calling the server multiple times.
This directive you might not wanna add on some buttons that you don't wish to track.

A: You could pass the argument to the function, that way you reutilize code:
HTML:
<button (click)="press('A')"></button>
<button (click)="press('B')"></button>

Typescript:
@Component({
  templateUrl:"my.html"
})
export class MyApp {

  press(arg: string) {
    sendServer(arg);
  }

}

Don't know if that's what you are looking for. Also I recommend creating a service for your server calls.

A: As @Reactgular comment, I have created a directive with button selector and click hostlistner.
@Directive({
  selector: 'button',
})
export class OnClickDirective {
  @HostListener('click', ['$event']) onClick($event: MouseEvent) {

    const location = $event.view.location ;
    const pathName = decodeURI(location.pathname);
    const innterHtml: string = this.el.nativeElement.innerHTML;

    // send pathName and innterHtml to server.
    //    :

  }

  constructor(private el: ElementRef) { }

}


text:
Q: CSS for specific text on Confluence I am wondering if there is a way to use custom css for some specific text on my confluence page (not using embedded HTML).

A: Sorry this is an old question, but for the sake of people who search for an answer to this question: you can use span or div macros and use the custom css to apply whatever style you want to their contents.
If necessary, you could create custom div and span classes to allow for multiple styles to be applied to selections of text.
EDIT: Here is an example of the wikimarkup you could use to do this
{div:class=customCss|style=float:left; margin-right:50px}
Custom text in a div
{div}

So you can either use the div class and apply a style in the custom css for the confluence space, or you can use an inline style for the div.

A: You can do this ...
{composition-setup}import.css=/download/attachments/123456789/custom.css
{composition-setup}

That's if you've stored a custom.css file as an attachement. You'd obviously need to replace 123456789 with the actual attachment number.
You can also link CSS on an external site (with an absolute URL), but if you have any automatic URL formatting, that tends to mess it up everytime you change the document.

A: I use a User Macro that renders the $body in HTML. Then I can put whatever HTML tags I want in the wiki page within the user macro tag.

A: There could be a way to reach what you want to reach, but there is some information missing (from you). What confluence allows is the following:

*

*If you have admin rights to the confluence wiki space, you could add there a custom style sheet that applies to all wiki pages. Else you could follow the answer of Mus.

*Then you should analyse the wiki page in source form. So load a wiki page you want to style, and look at the source of that wiki page in your browser. Depending on your browser, this may be CTRL-U or something similar. Here in chrome, the page menu says View page source.

*Try to find the defining selector for your wiki text you want to style in some form. A reasonable hack could be:

*

*Find a wiki style that is not used by others. I have experimented with ~subscript~.

*Find the HTML tags that are built by using that style. In my example, it was subscript.

*Use your custom style sheet to style text of that style.

*However, this may change the text where the style is used for its original sense :-(

A: You can specify custom CSS in your Confluence page via the div and span macros.
In recent Confluence versions (4.0 and later), you can do this as follows:

*

*Type {div} or {span}. On typing the closing brace }, auto-complete will convert the text to a macro.

*Left-click on the frame of the macro and select the Edit button

*Enter the custom CSS into the Style field and close the dialog

*Enter your text into the macro frame. It will then have the style you specified.


text:
Q: Showing a view in Navigation Controller after dismissing ZXingWidgetController I am having problem displaying a view in navigation controller after
dimissing ZXingWidgetController.
Here are the steps.

*

*Present ZXingWidgetController modally using
[self presentModalViewController:widController animated:YES];

*After scan result is returned in delegate
(void)zxingController:(ZXingWidgetController*)controller didScanResult:(NSString
*)resultString)

dismiss ZXingWidgetController and push a view controller in navigation controller.
[dismiss ZXingWidgetController: [self dismissModalViewControllerAnimated:YES];

Push a view controller in navigation controller:
ParsedResult *parsedResult = [[UniversalResultParser      parsedResultForString:resultString] retain];
self.result = [parsedResult retain];
self.actions = [self.result.actions retain];
ScanViewController *scanViewController = [[ScanViewController alloc]
initWithResult:parsedResult forScan:scan];
[self.navigationController pushViewController:scanViewController
animated:NO];
[scanViewController release];

But this results into navigation bar being hidden behind status bar
partially.
Please let me know how can I fix this issue?

A: You might wanna try going to the ZxingWidgetController.m
and changing setStatusBarHidden and self.wantsFullScreenLayout to NO
If that doesn't work, try adding the following to YourAppDelegate.m's didFinishLaunchingWithOptions: method :
[[UIApplication sharedApplication] setStatusBarHidden:NO animated:NO];


text:
Q: Linking to iOS simulator binaries on OSX I was curious what would happen if I linked to an iOS simulator framework in a Mac app. So I copied UIKit to it's own folder (so the Framework search path wouldn't include all the iOS simulator framework, as like CoreFoundation is both on Mac and iOS but has different headers), and dragged it into the link section in Xcode. The error Xcode gave me was:

building for MacOSX, but linking against dylib built for iOS Simulator
  file '/Users/jonathan/Desktop/macuikit/UIKit.framework/UIKit' for
  architecture x86_64

Both architectures are x86_64, so how can it tell the framework is specifically for the iOS simulator, I removed all references to iOS in things like Info.plist, even tried deleted everything but the UIKit binary, but the same error came up. Is there something in the binary it self that tells the linker which platform it can run on, rather than just the architecture? I looked at the Mach-O header but there is only fields for CPU type and subtype, and neither has a value for the simulator as expected.

A: After a little bit of digging, it turns out that the platform on which the library can run on is indeed specified in the binary. In fact, you can edit the binary in your favorite Hex editor and make the linker skip this check entirely.
This information is not specified in the Mach-O header (as you have already realized). Instead, it is specified as a load command type. You can see the available types by digging through the LLVM sources. Specifically, the enum values LC_VERSION_MIN_MACOSX and LC_VERSION_MIN_IPHONEOS look interesting.
Now, find the offset for this in our binary. Open the same in MachOView (or any other editor/viewer or your choice) and note the offset:

Once the offset is noted, jump to the same in a Hex editor and update it. I modified LC_VERSION_MIN_IPHONEOS (25) to LC_VERSION_MIN_MACOSX (24)
Save the updates and try linking again. The error should go away. Of course, you will hit other issues when you try to actually run your example. Have fun with LLDB then :)


text:
Q: Regarding read and write in kafka? I am a beginner and trying to get hang on kafka. I read from the documentation that Both the producer and the consumer requests to a partition are served on the leader replica. Does it mean consumer can't read from the followers of a leader. If not, why?. I think if we can read from followers it will improve more paralleism. Any insight into this would be of great help.

A: In the current design, a follower passively replicates the leader asynchronously. It's worth noting that not all replicas always keep sync with the leader, but only a part of them, namely, in-sync replicas(ISR). You could specify all the replicas as ISRs, but for the performance consideration, this will impact the producer throughput.
If client reads can be handled by any followers, there will be two possible cost: 1. Kafka must ensure all the replicas contain exactly the same message set at any time, which is a huge effort; 2. It slows down the producer greatly, since a message can be viewed as "committed" only after all the replicas acknowledge it.


text:
Q: tun device: message is not received by server process I set up two tun devices. The data that is written to each tun device is forwarded over a UDP socket to the other tun device using a simple loop:
// the tuntap device is created using these flags
ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
[...]

fd_set fd_list;

FD_ZERO(&fd_list);
FD_SET(fd1, &fd_list); // fd1 is the tun device
FD_SET(fd2, &fd_list); // fd2 is the udp socket

int fds[] = {fd1, fd2};
while(select(max(fd1, fd2)+1, &fd_list, NULL, NULL, NULL) > -1) {
    for(i = 0; i < 2; ++i)
        if(FD_ISSET(fds[i], &fd_list)) {
            nread = read(fds[i], buf, sizeof(buf));
            assert(nread > 0);

            ret = write(fds[(i+1)%2], buf, nread);
            if(ret == -1)
                perror("write():");
        }
}

After setting up the interfaces using
ifconfig tun0 10.0.0.1
ifconfig tun1 10.0.0.2

I send a ping from one device to the other
ping -I tun1 10.0.0.1

I can see that the IPv4 packet is received by the UDP socket for tun0 and this packet is correctly written to tun0. Also watching the traffic on tun0 using wireshark shows that the packet is received by tun0. However, no ping response packet is created.
I thought that might be a special case for ICMP packets but when I'm using
socat -d -d -d - TCP-LISTEN:2000,so-bindtodevice=tun0 &
sleep 1
echo 2 | socat -d -d -d - TCP:10.0.0.1:2000,so-bindtodevice=tun1

again no connection is established. the connect process (2nd socat call) only continues firing TCP-SYN packets and eventually times out. Again, watching the traffic on tun0 using wireshark shows that the TCP-SYN packet is delivered to the tun0 device.
Why is this packet not forwared to the socat TCP-LISTEN process so it can establish the connection??

A: Looks like this is a routing error.
When I run the program on two different machines, then the packets are routed through the tun0 device on each machine respectively and http://backreference.org/wp-content/uploads/2010/03/simpletun.tar.bz2 works fine. Running the programm on one machine twice does not work!


text:
Q: Нарисовать график функции Пожалуйста, помогите. Нужно нарисовать график функции x=wt (w-omega) в Flash Action script.
A: var w:int = 2; // эмуляция функции
var y:int = 0; // 't

var spr:Sprite = new Sprite(); // экранный объект на котором рисуем
spr.graphics.lineStyle(1, 0x00ff00); // толщина и цвет
spr.graphics.moveTo(0,0); // начальные коорды

for ( y=0; y<101;y++ ) //итерируем 't
{
    spr.graphics.lineTo(y * w, y); // линия в новую точку
}

stage.addChild(spr); // показываем наш спрайт


text:
Q: Change language for one user on Fedora 34 w/ XFCE I'm in a situation where I have to set the language for one user on Fedora 34 (with XFCE).
I found the settings to set the system language, but I can't figure out how to change the language for a user. The language locale in question is already installed (pl_PL.utf8), and I've set LANG=pl_PL.utf8 in ~/.config/locale.conf, but XFCE is still in english.
I read somewhere, that I should be able to select the locale while logging in, but it doesn't seem to work in Fedora. I'm not given the option to select a locale.
I cannot find it anywhere in the settings manager or in one of the hidden files in the user's home directory.
Just for clarification: I don't mean the system wide language! That one is quite easy to find, I mean the language for this one user, nothing else.

A: Fedora doesn't use this file.
You could edit your user ~/.bash_profile file and add this:
export LANG=pl_PL.utf8
Or use: ~/.config/environment.d/ (docs) - check man environment.d.
Gnome and KDE have built-in Control Centers to configure locale settings, other smaller DEs and window managers unfortunately need to be configured this way. It's sad there are no GUI tools to configure any DE in a unified way.


text:
Q: How does perf manages the execution of a process before reporting its statistics? Suppose I ran following perf command in the terminal to find number of page faults:
perf stat -e page-faults ls

I am not able to understand how perf executable (user space process) controls the execution of the ls executable.

*

*Does it stop ls executable before it exits and make some ioctl calls to fetch the results?

*If ls is executed and when it exits, all the data associated with its runtime is destroyed, so how does perf manages to access its data before its exit?


text:
Q: Posting free-form comments is possible without having enough reputation The current implementation of Stack Exchange allows us to comment on a particular question without even having enough reputation.
This can be done by exploiting the autocomment feature of Stack Exchange and then editing the comment as required.
Example:
How do I convert a string to a string literal in python? (I posted and edited this comment when my reputation was below 50)
I think this is a very serious problem as one can abuse any question by creating new accounts with a script and commenting as much as he want.

A: We patched this up in October of 2016. Since then, users without the "Comment Everywhere" privilege are no longer able to edit comments outside of their own questions and answers, even if the system does generate comments elsewhere on their behalf.

A: Agreed, users with less than 50 reputation should not be able to edit their comments, no matter how those comments were posted.
Another option is not allowing ordinary users to edit the auto-converted answers, even with high reputation. This will work too, and if needed the user can just delete and post new comment, or a new answer that won't get converted.
Would be happy to see either of those implemented.


text:
Q: Redirecting to some error page /**
 * @Route("/installation", name="installation")
 */
public function defaultAction()
{
    $this->checkPhpVersion();
    return $this->redirect($this->generateUrl('setdatabase'));
}

private function checkPhpVersion()
{
    if(phpversion() <= '5.5.0')
    {
        $message = 'aaa';
        return $this->render('myFooBundle:Bar:error.html.twig', ['message' => $message]);
    }
}

Well, I'd like the if instruction in the checkPhpVersion() method to display the error page and stop later executions.
The instruction is being called, but it seems that the view is not rendered properly, because I get redirected to the setdatabase controller (the end of defaultAction()), and I shouldn't.
The content of error.html.twig is not being displayed. Instead, as mentioned above, the setdatabase controller is called and its method's view appears.
What's wrong?

private function checkPhpVersion()
{
    if(phpversion() <= '5.5.0')
    {
        echo 1;
        exit();
        echo 2;
        $message = 'aaa';
        return $this->render('myFooBundle:Bar:error.html.twig', ['message' => $message]);
    }
}

This still changes nothing. However, deleting redirect statement and placing raw return array() there, deleting exit(), displays '1' and '2' integers, and some error according to the return array() mentioned.

A: The logic is wrong because you call a function returning a view, and then from the caller you proceed with a redirect (so both actions are triggered).
One solution would be to adapt your checkPhpVersion() function as follow:
/**
 * @Route("/installation", name="installation")
 */
public function defaultAction()
{
    if (!is_null($message = $this->checkPhpVersion()))
      return $this->render('myFooBundle:Bar:error.html.twig', ['message' => $message]);
    else
      return $this->redirect($this->generateUrl('setdatabase'));
}

private function checkPhpVersion()
{
    return phpversion() <= '5.5.0' ? 'aaa' : null;
}

If you want to leave the view generation inside the checkPhpVersion() function, you can use:
/**
 * @Route("/installation", name="installation")
 */
public function defaultAction()
{
    if(!empty($this->checkPhpVersion()))
      return new Response($content);
    else
      return $this->redirect($this->generateUrl('setdatabase'));
}

private function checkPhpVersion()
{
    if(phpversion() <= '5.5.0')
    {
        $message = 'aaa';
        return $this->renderView('myFooBundle:Bar:error.html.twig', ['message' => $message]);
    }
}

See: http://symfony.com/doc/current/book/controller.html#rendering-templates

A: If you're trying to stop further execution, use the PHP exit() function in your checkPhpVersion method after rendering the error page.


text:
Q: Selenium -maxSession for all Nodes We are using Selenium testing with protractor. For some tests we need to serialize the testing, so that maximum one Browser (in our case it's also an user) can be active. It's possible to limit the sessions with -maxSession parameter, but that just limits it for the current node. Is there a possibility to do that globally for every node or to start the nodes one after each other?

A: oh well it was easier than I thought. Parameter maxSessions: 1 in protractor.conf seems to work also with many nodes.


text:
Q: How to return all records using IN clause when parameter is empty? I'm passing a parameter like '1,2,3' to this statement:
SELECT *
FROM Negative
WHERE IdNegative IN (@IdNegative)

But I want to return all records (like the records with an id 1,2,3,4,5,6...) when the parameter is empty. Is there a way to do this?
Thank you.

A: Parameters and variables are not simply pasted into the query by the compiler. They are inserted as actual compiled values, so in this case the string 1,2,3 is never going to be equal to any of the numbers 1 2 3.
You need to declare as a table variable or as a Table-Valued Parameter
DECLARE @IdNegative TABLE (id int PRIMARY KEY);
INSERT @IdNegative VALUES (1),(2),(3);

SELECT *
FROM Negative
WHERE IdNegative IN (SELECT id FROM @IdNegative);


text:
Q: Why would a SQL Server query request the same lock twice and deadlock? I have SQL Server database that keeps getting deadlocked when two queries attempt to acquire locks they already own to the same table.

The above deadlock graph get's me very confused. Both PageLock are identical, which leads me to believe they are the same page. It seems to show that both processes already own locks to that page. The one on the left owns an Update (U) lock, while the one on the right owns and Intent Exclusive (IX) lock.
How is that even possible?
And why would they get blocked on acquiring locks they already own?
The query for the process on the left is:

The query for process on the right is:

A: Ideally we need to see the full XDL graph as well as the query plan to know for sure. Note that the Page Locks are not identical, they have different Page IDs.

But most likely what is going on here is as follows:

*

*The INSERT query is unlikely to be the culprit, because it's a simple single-row insert with no joins (although it is theoretically possible that an indexed view or a foreign key Assert could cause the deadlock)

*The UPDATE query probably does not have a supporting index. This would cause it to scan the whole table, unnecessarily locking a large number of rows, and creating more opportunities for deadlocks.

*The actual cause of the deadlock would then be that the UPDATE scans the table in one order, but the INSERT is going in a different order.

To solve this, you need to add an index to support the UPDATE. The most likely index is probably the following, but note that I don't know your table structure nor what other queries are going on, so a different index may prove better.
CREATE INDEX IX ON InventoryTotals
  (SellerID, GlobalOfferID) INCLUDE (OfferStatus);

The reason for this particular index is that the update looks at a single SellerID value, but GlobalOfferID seems to be an IN so it's probably multiple values. OfferStatus also needs to be there to avoid a key lookup, but it doesn't have to be a key column, it can be an INCLUDE.
Now the UPDATE will access the exact key it needs, and place a U-lock and then an X-lock only on that, so you should now avoid a deadlock as the access will always be in the correct order.

I note one final thing: it appears that the two statements have differently sized varchar parameters. This indicates you are relying on your driver to get the right data type and size, such as with SqlClient's AddWithValue. Never do this: always specify the data type and length/precision for each parameter.


text:
Q: How to set DataContext in a Dialog Window to its parent's DataContext I created a new Window which I then call using the following code:
NieuwSimulatie NiewSimulatieWindow = new NieuwSimulatie()
{
    Owner = this
};

bool? SimulatieAangemaakt = NiewSimulatieWindow.ShowDialog();

In the Window "NieuwSimulatie" I'd like to have the same DataContext as in my MainWindow, or I would like to DataBind the controls directly to the DataContext using RelativeSource I geuss, Ive tried:
<Controls:SplitButton x:Name="ProjectNaam"
                      DisplayMemberPath="ProjectNaam"
                      ItemsSource="{Binding Static.Projecten, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Controls:MetroWindow}}"/>

But this doesn't work.
Please help me either fix my DataBinding or help me set the DataContext of my Window to the DataContext that is behind MainWindow.

A: I've you have acces to your DataContext from where you create your window, how about that:
NieuwSimulatie NiewSimulatieWindow = new NieuwSimulatie()
{
    Owner = this,
    DataContext = YourDataContext;
};

bool? SimulatieAangemaakt = NiewSimulatieWindow.ShowDialog();

A: To do what you ask is typically done when creating the new window, because they are two Windows it's better to pass the context in...like this:
NieuwSimulatie MyNewWindow = new NieuwSimulatie(DataContent);
MyNewWindow.Show();

A: I think you need to do it like this :
NieuwSimulatie NiewSimulatieWindow = new NieuwSimulatie()

NiewSimulatieWindow.DataContext=this.DataContext;

bool? SimulatieAangemaakt = NiewSimulatieWindow.ShowDialog();


text:
Q: trouble with PHP's password_verify So, I'me coding a simple login system with php.
here's the registration code:
  if ($hash == $hash2) {

            $pass = password_hash($hash, PASSWORD_BCRYPT);

        } else {

          $message = "As password não são iguais.\\nTenta de novo.";
    echo "";
    echo "";
    echo "</script>";

        }

$sql = "INSERT INTO user (hash) VALUES ('$pass')";

the form for log in:
<form class="form" id="formLogin" style="color:#ffffff" action="stuff/login.php" method="post">

    password:
    <input name="password" id="password" type="password" placeholder="" style="background-color: #ffffff; color:#111111;" >

    <button type="submit" name="submit" id="btnLogin" style="padding-top: 5%; padding-bottom: 5%; color:#ffffff" class="btn btn-default outline center-block">Login</button>
</form>

My login.php (to simplify I'm using a fixed id of the database in the query and only a password field)
require_once("db.php");
require("password.php");

if (!empty($_POST['password'])) {

    $pass = htmlspecialchars($_POST['password']);
    $id = 1;
    $sql = "SELECT * FROM user WHERE id ='$id'";

    $res = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($res);
    $numRows = mysqli_num_rows($res);
    $h = $row['hash'];

    if($numRows == 1) {
        if(password_verify($pass, $h)) {
            header("Location: ../backoffice.php");
        } else {
            $message = $pass . "   " . $h;
            echo "";
            echo "</script>";

        }
    } else {
        $message = "a palavra-passe e/ou nome de utilizador est\343o errados.\\nTenta de novo.";
        echo "";
    }
};

When I echo the $message in the else part of the password_verify's if, to display both the input password and the database hash, they seem ok - the right string outcome from the log in form, and the correct hash stored in the database.
But yet, it doesn't work. Any suggestions?

A: It seems like it is a problem in your password_verify function. Maybe you are trying to match password with it's hash. Check id value and if there any character of the password is being skipped for htmlspecialchars function.


text:
Q: How to upgrade `pip3.8` for `python-3.8.2`? I have two python versions`(python-3.6 and python-3.8.2)` and two `pip`s (`pip3 and pip3.8`) respectively Whenever I upgrade the pip the python-3.6 version gets upgraded and when I do same for pip3.8 I get errors. Following snippets shows the detail:
users@user01:/mnt/d/codes/py38$ pip3.8 install --upgrade pip3.8
Collecting pip3.8
ERROR: Could not find a version that satisfies the requirement pip3.8 (from versions: none)
ERROR: No matching distribution found for pip3.8
Here's the system prompts:
WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
And when I run pip3.8 --versioin the following pops up:
pip 19.2.3 from /usr/local/lib/python3.8/site-packages/pip (python 3.8)
Need Help!!
Thank You!!

A: $ sudo pip3.8 install --upgrade pip

will give you the permissions you need.
If you aren't an administrator on the machine, you either need to su to one, or get them to run the command for you.


text:
Q: Child theme wordpress icon path I need to replace the below path to the icons with the new path to the child theme I have created.
The current path is:
<img width="32" height="32" src="<?php echo GDLR_PATH . '/images/' . $type . '/social-icon/' . $social_slug . '.png'; ?>" alt="<?php echo $social_name; ?>" />

and here is the full path to the icons of the child theme:
/the-child-theme/images/light/social-icon/(icon.png)

Could I have any assistance for that please?
Thank you in advance

A: Are you saying that you need to give a dynamic path for the child theme where you have moved the images?
If yes, then you can use this function : get_stylesheet_directory_uri()
It will give you the path to your child theme.
Example :
img src="'.get_stylesheet_directory_uri().'/images/light/social-icon/icon.png"


text:
Q: Modsecurity: removeWhitespace not working I have the following rule:
 SecRule REQUEST_HEADERS:Client-IP "@ipMatchFromFile test.txt"
"id:210487,t:none,t:urlDecodeUni,t:removeWhitespace,drop,msg:'IP-test'"

But When I run it I get the response:
T (0) urlDecodeUni: "111.22.33.44 " // note the space before the "
T (0) removeWhitespace: "111.22.33.44"  // perfect! The space has been removed
Transformation completed in 4 usec.
Executing operator "ipMatchFromFile" with param "test.txt" against REQUEST_HEADERS:Client-IP.
Target value: "111.22.33.44"  // target value has no space, hooray!
IPmatchFromFile: Total tree entries: 8, ipv4 8 ipv6 0
IPmatch: bad IPv4 specification "111.22.33.44 ".  // why, oh why, is the space back!
Operator completed in 4 usec.
Operator error: IPmatch: bad IPv4 specification "111.22.33.44 ".  // that space again!
Rule returned -1.
Rule processing failed.
Rule failed, not chained -> mode NEXT_RULE.

Please Stack Overflow legends; show me how I can fix it :-)

A: That should work, so looks like a bug. Can't say I've honestly tried to match an IP address that required transformation first.
Since it's not really an IP address you could switch to using @pmFromFile rather than @ipMatchFromFile. Note that the documentation warns explicitly that you need to use boundaries correctly here:

Because this operator does not check for boundaries when matching,
  false positives are possible in some cases. For example, if you want
  to use @pm for IP address matching, the phrase 1.2.3.4 will
  potentially match more than one IP address (e.g., it will also match
  1.2.3.40 or 1.2.3.41). To avoid the false positives, you can use your own boundaries in phrases. For example, use /1.2.3.4/ instead of just
  1.2.3.4. Then, in your rules, also add the boundaries where appropriate. You will find a complete example in the example:
# Prepare custom REMOTE_ADDR variable
SecAction "phase:1,id:168,nolog,pass,setvar:tx.REMOTE_ADDR=/%{REMOTE_ADDR}/"

# Check if REMOTE_ADDR is blacklisted
SecRule TX:REMOTE_ADDR "@pmFromFile blacklist.txt" "phase:1,id:169,deny,msg:'Blacklisted IP address'"

The file blacklist.txt may contain:
# ip-blacklist.txt contents:
# NOTE: All IPs must be prefixed/suffixed with "/" as the rules
#   will add in this character as a boundary to ensure
#   the entire IP is matched.
# SecAction "phase:1,id:170,pass,nolog,setvar:tx.remote_addr='/%{REMOTE_ADDR}/'"
/1.2.3.4/
/5.6.7.8/


text:
Q: Sort an array by 'price' value I have an array in the following format - I want to be able to sort this so the highest price is first - i've tried array_multisort() but I'm not having any luck so far.
    $working[33] = array('id' => '33', 'price' => '250.00');
    $working[34] = array('id' => '34', 'price' => '277.88');

Using some function to sort by price the end product should look as follows:- as the 277 price is greater than 250
    $working[34] = array('id' => '34', 'price' => '277.88');
    $working[33] = array('id' => '33', 'price' => '250.00');

A: Sorting using usort :
usort($working, function($a, $b) {
    return $a['price'] < $b['price'] ? 1 : -1;
});

A: use below function to get your problem resolve
    function multisort (&$array, $key) {
         $valsort=array();
         $ret=array();
         reset($array);
         foreach ($array as $ii => $va) {
            $valsort[$ii]=$va[$key];
         }
         asort($valsort);
         foreach ($valsort as $ii => $va) {
             $ret[$ii]=$array[$ii];
         }
         $array=$ret;
     }

multisort($multiarr,"order");

A: You can do it with array_multisort
Examples on the documentation.

A: Remove quotes OR use numeric sort.
String "24" is greater than "1834" because 2 is greater than 1.
My solution
$working[33] = array('id' => '33', 'price' => '250.00');
$working[34] = array('id' => '34', 'price' => '277.88');
$working[35] = array('id' => '35', 'price' => '1289.57');
$working[36] = array('id' => '36', 'price' => '15.42');

foreach ($working as $key => $row) {
    $price[$key] = $row['price'];
}

array_multisort($price, SORT_NUMERIC, $working);

var_dump($working);

Output
array(4) {
  [0]=>
  array(2) {
    ["id"]=>
    string(2) "36"
    ["price"]=>
    string(5) "15.42"
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(2) "33"
    ["price"]=>
    string(6) "250.00"
  }
  [2]=>
  array(2) {
    ["id"]=>
    string(2) "34"
    ["price"]=>
    string(6) "277.88"
  }
  [3]=>
  array(2) {
    ["id"]=>
    string(2) "35"
    ["price"]=>
    string(7) "1289.57"
  }
}

A: See Sorting arrays in php to solve your problem

A:     usort($working, function ($a, $b) {
        return bccomp($a['price'], $b['price'], 2);
    });


text:
Q: pylintrc file not being detected in LiClipse This is the command that is run by LiCLipse
PyLint: Executing command line: /usr/local/bin/pylint --rcfile=.pylintrc /Users/yogibear/google-python-exercises/basic/string2.py

This is the option I am using to add a pylint configuration file in LiCLipse. I am using the latest version of LiClipse. Relative path.
 --rcfile=.pylintrc

The contents of the file are
[FORMAT]
ident-string='  '

Path to the rcfile is:
/Users/yogibear/google-python-exercises/basic/.pylintrc

It doesn't seem to be detecting the file since it still complains about my python source code file having 2 tabs ?
I have named the pylint configuration file as '.pylintrc'.
absolute path to the file works. Its just when I only specify the filename, it can't find it. Why aren't relative paths working ? What is the project root in eclipse pydev ?
New to pylint so not sure whats going on.

A: PyLint is always run in the project root, so, for --rcfile=.pylintrc, the .pylintrc file must be in the project root (right next to .project and .pydevproject).


text:
Q: Allow a class to be casted as another class in Java I have a very simple class, say
public class myInt {
    private Integer myint; // public?

    public myInt(Integer i) {
        this.myint = i;
    }

    public Integer getmyInt() {
        return myint;
    }
}

Now I need to use some functions that take as argument ArrayList<Integer>. Is it somehow possible to make my class castable as Integer?

A: In Java, when you say "primitive type" you refer specifically to certain types of variable (e.g. int, char), so in this case, if you want a literal answer, then the answer is "no", you can't cast myInt to Integer (btw, Integer is not a primitive type, whereas int is)
However if you want to achieve what you state you can create an empty ArrayList<Integer> and then query each of your myInt objects and call myInt.getmyInt() (since that returns an Integer) and add them to your ArrayList<Integer>.
For example, something like this:
ArrayList<Integer> myNumbersArray= new ArrayList<>();
myInt myNumber = new myInt(4);
myNumbers.add(myNumber.getmyInt());

Although I'm not sure why would you need to do this since you are basically taking an integer, wrapping it in a different object and then unwrapping it, so you could as well avoid the middle step, unless you are for some other reason using that middle construct.

A: If the cast needs to be supported there should be a relation(super/child) between the classes.Even with the same there can be run time errors while casting.
this will be a useful link
http://www.wideskills.com/java-tutorial/java-object-typecasting


text:
Q: URL decoding resulting in question marks in tomcat I'm calling a url like this:
http://localhost:8080/abc/income?content=%E0%B6%B8%E0%B6%9C%E0%B7%99+%E0%B6%B1%E0%B6%B8+%E0%B6%BD%E0%B6%9A%E0%B7%8A%E0%B6%B8%E0%B7%8F%E0%B6%BD%E0%B7%8A.&SOURCE_PRV=%20HTTP/1.1

and in the backend (tomcat) I'm decoding the string.
But I get the content as "??? ?? ???????" (several question marks).
How can I fix this?

A: The java.net.URI class can help; in the documentation of URL you find
Use one of the constructors with more than one argument, like:
URI uri = new URI(
    "http",
    "search.barnesandnoble.com",
    "/booksearch/first book.pdf",
    null);

URL url = uri.toURL();
//or String request = uri.toString();


text:
Q: Policy Injection Application Block in real world apps? The PIAB of the Microsoft Enterprise Library looks like it could be used for some pretty cool things.  Many people were questioning how it would perform in real world applications, due to its use of remoting-based interception techniques.  I haven't heard much about it recently and am wondering if anyone has had good or bad experiences from a performance standpoint to share.

A: Wow, not a single response in over a year.  I guess that's my answer!


text:
Q: MySql query to get rows with only one connected row I have a tables like that:
Products
ID | Name
1  | Prod1
2  | Prod2

Product_history
ID | Product_id | quantity | order_id | date
1  | 1          | 10       | 1        | 2014-01-01 10:00:00
2  | 1          | 11       | 1        | 2014-01-01 11:00:00
3  | 1          | 20       | 2        | 2014-01-01 09:00:00
4  | 2          | 50       | 2        | 2014-01-01 09:00:00

I can't create query witch will return me all products with sum of quantities of each order by only with last date. In this example I want  to return:
product_id | quantity
1          | 31 (11 + 20)
2          | 50

Can you help me?

A: select p1.product_id, sum(p1.quantity)
from product_history p1
join
(
  select product_id, max(date) as date
  from product_history
  group by product_id
) p2 on p1.product_id = p2.product_id and p1.date = p2.date
group by p1.product_id

A: Here is an approach that uses not exists:
select ph.product_id, sum(ph.quantity)
from product_history ph
where not exists (select 1
                  from product_history ph2
                  where ph2.order_id = ph.order_id and
                        ph2.product_id = ph.product_id and
                        ph2.date > ph.date
                 )
group by ph.product_id;

If your tables are large, you want a composite index on product_history(order_id, product_id, date) for performance.


text:
Q: Support vector machine plotting I was trying to plot a SVM classification. However I encountered a problem that I have no idea how to fix. I looked at documentation and some videos but still stuck. Here is my code
library(ISLR)
svm.oj2 <- svm(Purchase~.,data=OJ,kernel='linear',cost=1,scale = F)
plot(svm.oj2,data=OJ)

Here is the error:
 Error in plot.svm(svm.oj2, data = OJ) : missing formula.

Really appreciate any help

A: I think this is what you are trying to do:
library(ISLR)
library(e1071)
svm.oj2 <- svm(Purchase~.,data=OJ,kernel='linear',cost=1,scale = F)

plot(OJ, col = 1:1000 %in% svm.oj2$index + 1)


text:
Q: Populate dropdownlist using stored proc based on user logged in I'm just learning asp.net so I may be wrong on how I'm doing this so let me know if there is a better way.
I have a "portal", where a user logs in and then they have a dropdownlist of all their sites they manage.
I want to populate the dropdown box using a stored proc I created which is based on the user logged in.
I used the built in createuserWizard which stores the users in the database. I created another table that has all the sites and a 3rd table to link the sites and users together.
Here is the dropdown list

    <asp:DropDownList ID="DropDownListAClient" runat="server"
         OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
         DataSourceID="SqlDataSourceSitePicker" DataTextField="SiteName"
         DataValueField="SiteName">
    </asp:DropDownList>

    <asp:SqlDataSource ID="SqlDataSourceSitePicker" runat="server"
         ConnectionString="<%$ ConnectionStrings:MainAppDB %>"
         SelectCommand="portal_SitePicker" SelectCommandType="StoredProcedure">

         <SelectParameters>
               <asp:Parameter Name="portaluserid" Type="String" />
         </SelectParameters>

    </asp:SqlDataSource>

Here is the code for the stored procedure

ALTER PROCEDURE [dbo].[portal_SitePicker]
    -- Add the parameters for the stored procedure here
    @portaluserid varchar
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT SiteName
FROM dbo.aspnet_UserMap, dbo.Sites
WHERE dbo.Sites.SiteID = dbo.aspnet_UserMap.SiteID
and dbo.aspnet_UserMap.UserID = @portaluserid
END

If I test the stored proc it pulls the correct sites, but I'm not sure how to get the userid value from the current logged in user.
Any suggestions?

A: When you pass the parameter, it is beeter to set the length for you parameter for varchar in SQL and the asp page. You may try to  add the size on the parmeter like tht  on the asp page
 and @portaluserid varchar (25) and store procedure


text:
Q: ffmpeg android: change the speed of video and audio I am working on Android platform with ffmpeg, I've built the ffmpeg and run as 'run-time' command for my android app.
I've tested some function like video trim, it's working :
ffmpeg -i /sdcard/vpai/in.mp4 -ss 5 -t  5 -c:v copy -c:a copy /sdcard/vpai/out.mp4

merge video and audio, also working:
ffmpeg -i /sdcard/vpai/in.mp4 -i /sdcard/vpai/in.mp3 -c:v copy -c:a copy /sdcard/vpai/out1.mp4

But when I try to speed up the video, it's not working, the command is:
ffmpeg -i /sdcard/vpai/in.mp4 -filter_complex '[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]' -map '[v]' -map '[a]' /sdcard/vpai/output.mp4

I execute the exact same command on desktop, its working fine, but not working on the Android...
The error message:
Invalid stream specifier:"[v]".
Last message repeated 3 times
Stream map "[v]" matches no streams.
Any one can help?


text:
Q: How to sort a Map>> by the Set size sum? How can I sort a Map(String, List(Set(Long))) by the Set size sum?
I have a HashMap like this:
myMap.put("monday", [[3215, 5654], [5345], [3246, 7686, 4565]]) // 6 Long elements in total
myMap.put("tuesday", [[3215, 5654], [5345, 2879, 6734], [3246, 7686, 4565]]) // 8 Long elements in total
myMap.put("wednesday", [[9845, 2521], [0954]]) // 3 Long elements in total

I expect the myMap sorted like this:
("tuesday", [[3215, 5654], [5345, 2879, 6734], [3246, 7686, 4565]]) // 8 Long elements in total
("monday", [[3215, 5654], [5345], [3246, 7686, 4565]]) // 6 Long elements in total
("wednesday", [[9845, 2521], [0954]]) // 3 Long elements in total

A: Use LinkedHashMap for sorting:
Map<String, List<Set<Long>>> result = map.entrySet()
    .stream()
    .sorted(Comparator.comparingInt(e->e.getValue().stream().mapToInt(Set::size).sum()))
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

A: You would be able to perform some operations on it, but keeping a HashMap sorted on value is indeed not possible.
However, if you know the operations you want to perform on it, you may use the following solution.
myMap.entrySet()
     .stream()
     .sorted((entry1, entry2) -> {
         Integer sum1 = getSumOfSetCount(entry1.getValue());
         Integer sum2 = getSumOfSetCount(entry2.getValue());
         return Integer.compare(sum1, sum2);
     })
     .forEach(entry -> // perform operation);

With getSumOfSetCount() being
public int getSumOfSetCount(List<Set<Long>> list) {
    return (int) list.stream()
                     .flatMap(Stream::of)
                     .count();
}


text:
Q: Correct handling of AttributeError in __getattr__ when using property I have a difficulty implementing properties and __getattr__ so that
when an error happens, it is reported correctly. This is my MWE (python 3.6):
class A:

    @property
    def F(self):
        return self.moo # here should be an error

    @property
    def G(self):
        return self.F

    def __getattr__(self, name):
        print('call of __getattr__ with name =', name)
        if name == 'foo':
            return 0
        raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))

a = A()
print(a.G)

The output is as follows:
call of __getattr__ with name = moo
call of __getattr__ with name = F
call of __getattr__ with name = G
Traceback (most recent call last):
  line 18 in <module>
    print(a.G)
  line 15, in __getattr__
    raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))
AttributeError: 'A' object has no attribute 'G'

But the error that should be raised is:
AttributeError: 'A' object has no attribute 'moo'

I know that properties and attributes in the __dict__ are attempted before __getattr__ is called in an error-free scenario.

*

*It seems incorrect to me that when a property exists but fails, __getattr__ is still attempted instead of letting the error from the property to go through. How can this be avoided?

*The initial error message that was generated about failing to get attribute 'foo' has been lost. The final error message 'A' object has no attribute 'G' is particularly misleading and annoying. How to implement __getattr__ in order to see the initial error?

*(EDIT) A related problem is simultaneously to achieve that
hasattr(a, 'moo') returns False while hasattr(a, 'G') returns True or raises an exception of the missing 'moo' attribute. Does that make sense?

A: What is happening?
First, a little heads up as to why this happens. From the doc on __getattr__:

Called when the default attribute access fails with an AttributeError [...] or __get__() of a name property raises AttributeError.

In this case, since you are using @property, we are looking at an AttributeError raised from the __get__ method of the property F when trying to recover self.moo. This is what your call stack looks like at that moment.
__main__
a.G.__get__
a.F.__get__
a.__getattr__ # called with 'moo' <-- this is where the error is raised

The attribute getter protocol sees an error being raised from inside a.F.__get__, it thus fallback on calling a.__getattr__('F') and that despite the fact the error had been raised because of 'moo'. The same then happens for a.G.__get__
This behaviour is considered normal in Python, since the top-most property that failed to return a value is indeed a.G.
Solution
Now what you want is for an AttributeError raised by a __get__ method to bubble up instead of being caught. To do that you need not to have a __getattr__ method.
Thus, in this particular case, what you want to use is __getattribute__ instead.
Of course, with this solution you have to make sure yourself not to override an existing attribute.
class A:

    @property
    def F(self):
        return self.moo # here should be an error

    @property
    def G(self):
        return self.F

    def __getattribute__(self, name):
        print('call of __getattribute__ with name =', name)
        if name == 'foo':
            return 0
        else:
            return super().__getattribute__(name)

Example
A().G

Output
call of __getattribute__ with name = G
call of __getattribute__ with name = F
call of __getattribute__ with name = moo

Traceback (most recent call last):
...
AttributeError: 'A' object has no attribute 'moo'

A: Here's a hacky solution, replacing the AttributeError with another exception type:
from functools import wraps

def no_AttributeError(f):
    @wraps(f)
    def wrapped(self):
        try:
            return f(self)
        except AttributeError as e:
            raise Exception('AttributeError inside a property getter') from e
    return wrapped

class A:

    @property
    @no_AttributeError
    def F(self):
        return self.moo # here should be an error

    @property
    @no_AttributeError
    def G(self):
        return self.F

    def __getattr__(self, name):
        print('call of __getattr__ with name =', name)
        if name == 'foo':
            return 0
        raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))

a = A()
print(a.G)

This results in the following output:
call of __getattr__ with name = moo
Traceback (most recent call last):
  File ".\test_getattr_redir.py", line 7, in wrapped
    return f(self)
  File ".\test_getattr_redir.py", line 17, in F
    return self.moo # here should be an error
  File ".\test_getattr_redir.py", line 28, in __getattr__
    raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))
AttributeError: 'A' object has no attribute 'moo'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ".\test_getattr_redir.py", line 31, in <module>
    print(a.G)
  File ".\test_getattr_redir.py", line 7, in wrapped
    return f(self)
  File ".\test_getattr_redir.py", line 22, in G
    return self.F
  File ".\test_getattr_redir.py", line 9, in wrapped
    raise Exception('AttributeError inside a property getter') from e
Exception: AttributeError inside a property getter

As an addendum, to make it explicit why Python does what it does, here's an excerpt from the documentation:

[__getattr__ is called] when the default attribute access fails with an AttributeError (either __getattribute__() raises an AttributeError because name is not an instance attribute or an attribute in the class tree for self; or __get__() of a name property raises AttributeError). This method should either return the (computed) attribute value or raise an AttributeError exception.

(It looks like you know this but I think it's good to have it written out for other people running into the same issue.)
So that means when self.moo raises an AttributeError, it results in A.__getattr__(a, 'F') being called, which results into another AttributeError

A: Given the answers above, I have tried the following solution for the case when __getattr__ is already defined by the base class P that we cannot change.
class P:
    def __getattr__(self, name):
        print('call of __getattr__ with name =', name)
        if name == 'foo':
            return 0
        raise AttributeError("Cannot recover attribute '{}'".format(name))

class A(P):
    e = None

    @property
    def F(self):
        return self.moo

    @property
    def G(self):
        return self.F

    def __getattr__(self, name):
        raise A.e

    def __getattribute__(self, name):
        try:
            return object.__getattribute__(self, name)
        except AttributeError as e1:
            try:
                return P.__getattr__(self, name)
            except AttributeError as e2:
                A.e = AttributeError(str(e1) + ' -> ' + str(e2))
                raise AttributeError

a = A()
print(a.G)

It replicates what python does when looking for attributes: the order of calls and semantics are kept. It only changes the final error message to
AttributeError: 'A' object has no attribute 'moo' -> Cannot recover attribute 'moo' -> Cannot recover attribute 'F' -> Cannot recover attribute 'G'
However, it might be causing more problems in the derived code than it is solving, so I don't know.


text:
Q: How Do I Add An Alpha Channel To My PNG Files Using ImageMagick? I have several Mac apps already created using another tool that I need to create Apple images for. They were created as PNG files without an alpha channel and stored in a folder.
I attempted to do the following command:
iconutil -c icons myfolder.iconset

I got multiple errors like below:
iconutil error: Unsuported image format

After reading this blog post along with a couple of posts on Stack Overflow I saw that I needed to have an alpha channel on my images. This is not stated in the Apple Developer documentation.
I tried using Preview for this but from the research I have done, including watching several videos I would have to remove a color which would mess up my icons, especially the smaller ones. My icons have a black background and attempting to remove what little white is on them would be a nightmare for the smaller icons.
There is a comment on this link by David Grayson that stated that ImageMagick could be used to add the alpha channel. The comment said that if I executed the following command for each png file that should work.
convert old_icon_16x16.png -define png:color-type=6 icon_16x16.png

However when I execute this I get the following error:
Abort trap: 6

I then went to this link referenced by the main ImageMagick website for examples. I tried the following command.
convert old_icon_16x16.png -alpha off -alpha on icon_16x16.png

I got the following error:
Abort trap: 6

I'm not sure where to go from here.

A: If you are getting Abort or Segmentation Faults, it smacks of a mismatch in the compiling/building/linking of your ImageMagick.
I would suggest you remove whatever you have installed of ImageMagick, and start afresh with homebrew which is the simplest way of installing ImageMagick on OSX. Basically, you go to the Homebrew website and copy and paste the one-liner into Terminal to install it (I don't want to show the line here in case it changes in future and this gets out of date).
Once you have homebrew installed, it is just a matter of:
brew install imagemagick

If, you want to see the options for supporting X11, TIFF, fftw etc, just run:
brew options imagemagick

Output
--with-fftw
    Compile with FFTW support
--with-fontconfig
    Build with fontconfig support
--with-ghostscript
    Build with ghostscript support
--with-hdri
    Compile with HDRI support
--with-jp2
    Compile with Jpeg2000 support
--with-liblqr
    Build with liblqr support
--with-librsvg
    Build with librsvg support
--with-libwmf
    Build with libwmf support
--with-little-cms
    Build with little-cms support
--with-little-cms2
    Build with little-cms2 support
--with-openexr
    Build with openexr support
--with-openmp
    Compile with OpenMP support
--with-pango
    Build with pango support
--with-perl
    enable build/install of PerlMagick
--with-quantum-depth-16
    Compile with a quantum depth of 16 bit
--with-quantum-depth-32
    Compile with a quantum depth of 32 bit
--with-quantum-depth-8
    Compile with a quantum depth of 8 bit
--with-webp
    Build with webp support
--with-x11
    Build with x11 support
--without-freetype
    Build without freetype support
--without-jpeg
    Build without jpeg support
--without-libpng
    Build without libpng support
--without-libtiff
    Build without libtiff support
--without-magick-plus-plus
    disable build/install of Magick++
--without-opencl
    Disable OpenCL
--HEAD
    Install HEAD version

Then you can either do:
brew install imagemagick --with-hdri --with-librsvg

or, if you have already installed ImageMagick, you can change your installed options with:
brew reinstall imagemagick --with-x11 ...

As Glenn points out in the comments, an easier command than the one you are using is probably:
convert old_icon_16x16.png png32:icon_16x16.png

Also, note that convert becomes magick from Version 7 onwards - though homebrew is still delivering Version 6 at the moment.


text:
Q: Html not displaying values through knockout observable. I am working on a video player app, I have set up various video player app functions like play,pause,forward and rewind.
I am facing issue with the fast forward button, when I hit fast forward The Html DOM does not display the first fast forward i.e 1.5x and when I hit again for 2x, it displays that.. I need help figuring out, why it would not 1.5x ?
Here is my html

Here is the corresponding javascript code !!
self.playbackRateIndicator = ko.observable();
    self.playbackRate0 = 1.5;
    self.playbackRate2 = 2.0;
    self.playbackRate1 = 1.0;
    self.playbackRate4 = 4.0;
    self.playbackRate8 = 8.0;

    self.fastForwardClick = function () { self.fastForward(null); }

    self.fastForward = function (playbackRate) {
        if (videoSelector().paused) {
            videoSelector().play();
        }

        if (self.intervalRewind() != null) {
            clearInterval(self.intervalRewind());
            self.intervalRewind(null);
        }
        var newPlaybackRate = self.playbackRate1;
        switch (videoSelector().playbackRate) {

              case self.playbackRate1:
                newPlaybackRate = self.playbackRate0;
                break;

            case self.playbackRate0:
                newPlaybackRate = self.playbackRate2;
                break;
            case self.playbackRate2:
                newPlaybackRate = self.playbackRate4;
                break;
            case self.playbackRate4:
                newPlaybackRate = self.playbackRate8;
                break;
            case self.playbackRate8:
                newPlaybackRate = self.playbackRate1;
                break;
            default:
                newPlaybackRate = self.playbackRate1;
                break;
        }

Help is appreciated. Thank you!!

A: In the code you posted, you never set a value for playbackRateIndicator. In your switch, you set a local variable. At the end of the switch, you should transfer that value into your observable:
playbackRateIndicator(newPlaybackRate);

I cannot explain why you get 2x and don't get 1.5x because I cannot explain why you would ever see any change, since you never set the associated observable.
It is always a good idea to try to create a Minimal Complete Verifiable Example of problem code - the simplest Fiddle you can write that demonstrates the problem. In the first place, you will often figure out for yourself what is going on, but if not, it gives us something to work with where we can be sure to find the problem.
Here is how I would do it:

vm = {
  rates: [1,1.5,2,4,8],
  playbackRateIndicator: ko.observable(),
  intervalRewind: ko.observable(null),
  fastForwardClick: function () {
    console.log("Forward!");
    let currentRateIndex = vm.rates.indexOf(vm.playbackRateIndicator()) + 1;

    if (currentRateIndex > vm.rates.length - 1) {
      currentRateIndex = vm.rates.length - 1;
    }
    vm.playbackRateIndicator(vm.rates[currentRateIndex]);
  }
};

ko.applyBindings(vm);
.unstyled-list {
  list-style: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>


text:
Q: Verilog Tri-State Issue (Xilinx Spartan 6) Referring to my earlier question here, I've been utilizing tri-states to work with a common bus. I still appear to have some implementation issues.
The tri-states use this type of code:

assign io [width-1:0] = (re)?rd_out [width-1:0]:{width{1'bz}};

Synthesis and translation goes well. No warnings or errors I wasn't expecting (I was expecting some since this is only a trial run and most of the components don't do anything and will hence be left unconnected). But when I actually try to implement it, all busses (there are three) output a 1111111111111111, or a -1, as converted by my binary to BCD converter. I checked if it really the case by instructing the control matrix to halt if the instruction received on the bus is -1, and it did halt.
The warning I receive for the tri-state being converted to logic is:

Xst:2040 - Unit Neptune_I: 16 multi-source signals are replaced by logic (pull-up yes)
Xst:2042 - Unit alu: 16 internal tristates are replaced by logic (pull-up yes):

And so on. Neptune_I is the top module, and I believe the multi-source signals it's referring to are the busses.
I have a doubt whether the pull-up yes is the root of this problem. Is it simply pulling everything up, causing it to be -1 all the time? But this does not make sense to me, because when the tri-state is activated, the signal should be controlled by whatever entity it is supposed to be controlled by.
I would like to take the time to replace the code with logic instead of the tri-states, but I'm unsure how to proceed.
Any help would be appreciated.

A: Are these signals going off-chip?  Or are they internal to your FPGA?  If the answer is the latter, you need to change your code.  Modern FPGAs (like Spartan 6) no longer support internal tri-state buffers.  They only exist for off-chip signals.
You need to write all of you internal code to avoid tri-state buffers.  Create dedicated paths between components, no bidirectional interfaces.


text:
Q: How to use addExtraLib in Monaco Editor with EChart type definition
 const [state, setState] = useState(test);
    const monaco = useMonaco();

    const handleChange = (props: any, event: any) => {
        setState(props);
        // configRef.current = props;
    };

    useEffect(() => {
        if (monaco) {
            monaco.languages.typescript.typescriptDefaults.addExtraLib(
                `declare let options: EChartsOption`,
                `node_modules/echarts/types/dist/echarts.d.ts`
            );
        }
        console.log(monaco);
    }, [monaco]);

I'm implementing the editor part of the EChart sample page.
I want to implement partial autocompletion in monaco editor.
What should I do? I tested it by referring to the monaco editor playground and other stack overflow questions, but failed


text:
Q: Configuration store variation with React/redux and thunkMiddleware I've been through many examples to understand how Redux-Thunk works and most the time the store is configured in a various way. I guess there's the old way or the new way but I'm kind of lost. Here is three pattern that I've identified. If someone can explain me the differences between them :
The simple way :
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'

    const loggerMiddleware = createLogger()

    const store = createStore(rootReducer, applyMiddleware( thunkMiddleware, loggerMiddleware));

the Official Reddit Async Exemple way (here) :
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'

const loggerMiddleware = createLogger()

export default function configureStore(preloadedState) {
  return createStore(
    rootReducer,
    preloadedState,
    applyMiddleware(
      thunkMiddleware,
      loggerMiddleware
    )
  )
}

the old way ?
import {compose, createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';

const createAppStore = compose(
    applyMiddleware(thunkMiddleware)
)(createStore);

export default function configureStore(initialState){
    const store = createAppStore(rootReducer, initialState);

    return store;
};

From there I have at least four questions :

*

*Do we still need to use compose ? I only find it in "old" exemple ?

*Is there any differences between import ReduxThunk from
'redux-thunk' and import thunkMiddleware from 'redux-thunk' ?

*Does the simple way is also correct ?

*I don't understand the preloadedState pattern from the Reddit Async Exemple.

thanks.

A: The signature for createStore is createStore(reducer, [preloadedState], [enhancer]).
preloadedState is an initial state you load before you initialize your app. For instance, if you prerender your first page on a server and want to pass app state as a JSON inside your HTML. Sometimes you need to fetch this state asynchronously that is where the second example is useful. You fetch your state and create a store using that state in the callback of your ajax call.
The third argument.
enhancer is a higher-order function that composes a store creator to return a new, enhanced store creator. applyMiddleware is a store enhancer shipped with redux. If you want to combine multiple store enhancers you need to use compose function.
For instance, redux-devtools-extension for chrome is an enhancer so to use it in your app you would need compose function
let store = createStore(reducer, initialState, compose(
  applyMiddleware(...middleware),
  window.devToolsExtension ? window.devToolsExtension() : f => f
));

When you import something from 'redux-thunk' you use default export so you can name your variable as you want. It doesn't matter.
A simple way is also correct if you don't need anything fancy it would work just fine.


text:
Q: Why is the $injector empty when using UpgradeComponent I try to upgrade from angular1 to angular2 by bootstraping hybrid both ng1 and ng2.
Here is the code: https://plnkr.co/edit/3jrnPyVc8WN2a4crUJFp?p=preview
When I run this example I get an error saying:
 Cannot read property 'get' of undefined
at HeroDetailDirective.UpgradeComponent (https://unpkg.com/@angular/upgrade/bundles/upgrade-static.umd.js:512:43)
at new HeroDetailDirective (https://run.plnkr.co/QOdaB9QdPbHLfQe9/app/main.0.ts!transpiled:45:16)
at new Wrapper_HeroDetailDirective (/AppModule/HeroDetailDirective/wrapper.ngfactory.js:7:18)

When I debug I see that in the UpgradeComponent the $injector is empty:
function UpgradeComponent(name, elementRef, injector) {
        this.name = name;
        this.elementRef = elementRef;
        this.injector = injector;
        this.controllerInstance = null;
        this.bindingDestination = null;
        this.$injector = injector.get($INJECTOR);

Any ideas why?
Thank you for your help.

A: Found the problem.
I defined to bootstrap the AppComponent:
@NgModule({
  imports: [ BrowserModule, UpgradeModule ],
  declarations: [ AppComponent, HeroDetailDirective ],
  bootstrap: [  AppComponent  ]
})
class AppModule {
  ngDoBootstrap() {}
}

When I removed the bootstrap definition, it worked:
@NgModule({
  imports: [ BrowserModule, UpgradeModule ],
  declarations: [ AppComponent, HeroDetailDirective ]
})
class AppModule {
  ngDoBootstrap() {}
}

I didn't realise that a hybrid app is always bootstrapped by ng1. This articel helped me a lot: https://www.softwarearchitekt.at/post/2016/11/15/using-ngupgrade-with-aot-to-optimize-performane.aspx


text:
Q: How can I maximize return on crafting During crafting, there are four different actions available, and four different indicators that these actions manipulate.
At what levels of Heat, Durability, and Progress should each action be taken in order to maximize the final quality of the product, and what might the final stats of a product of a given quality be?
Note: This doesn't need to result in perfect items every time, or anything like that, even a pattern that will tend towards better quality goods would be helpful.

A: It's impossible to give a concrete answer to what steps should be taken in which order, as the effects of each kind of action are randomized unless they give an actual number.
The changes listed in the UI are a general guideline - but I've had times when choosing Strong twice would get immediately to the :WARNING: heat level, and times when choosing Strong three times didn't even get to WARNING.
One way to think about crafting is like this: Durability is a resource you spend in exchange for certain quantities of Quality, Heat and Progress depending on which option you pick; your ultimate goal is to maximize Quality before Durability reaches zero.
You have to time these two things together in order to reach the end of the Progress bar at exactly that point - an ideal crafting reaches the end of the Progress bar with Durability at 1 and Quality as high as you can get it.
Heat only matters insofar as too much of it will halve your Durability, which is obviously bad, and if you overheat an item while crafting you won't gain crafting skill.
Further, Progress can also be an enemy; after all, the crafting ends as soon as the progress bar fills up. If you still have more than 1 Durability at that point, it goes to waste.
Therefore, my preferred strategy for low-level crafting is as follows:

*

*Start out by choosing Strong, to gauge how much heat it will generate in this crafting

*Alternate Strong and couple of Light to build progress and keep heat down until I'm near the end of the Progress bar

*Once I'm close to the end of the Progress bar, start adding in Wait to keep Progress down

*Once Durability is low (20ish) start using Medium to finish the craft

Note that I mentioned "low-level" - you unlock other crafting options as you level up, and you can upgrade your hammer with gold. The new crafting options don't look particularly useful, but since an upgraded hammer produces more quality per strike there might be some interesting strategies for boosting quality in there.


text:
Q: Optimizing HTML Parsing in VBA I have some VBA code that makes a request to https://nt3-s.zacks.com/fundamreports/Default.aspx and extracts all the data to a worksheet. My issue is that my parsing technique takes a very long time. Does anyone have any suggestions on how I can improve what the code below does? Maybe I should utilize QuerySelectorAll() or some other method...
Sub Financials(ticker, SheetName As String)
Dim XMLPage As New MSXML2.XMLHTTP60
Dim RP1, RP2, QP1, QP2, QP3, QP4, QP5, QP6 As String
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim HTMLRow, HTMLCell As MSHTML.IHTMLElement
Dim i As Integer
Dim r, c, offset, shift As Integer

'Application.ScreenUpdating = False

shift = 50

' STANDARDIZED FINANCIAL STATEMENTS

' Generate income statements
'============================

XMLPage.Open "Post", "https://nt3-s.zacks.com/fundamreports/Default.aspx", False

' Header
XMLPage.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

' Body Parameters
' Required parameters so every table value can be editted
RP1 = "__VIEWSTATE=%2FwEPDwUJNDg5NjgzODkyD2QWAgIDD2QWAgIBD2QWBAIPDxAPFgIeB0VuYWJsZWRnZGRkZAITDxAPFgIfAGdkZGRkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQhidG5FeGNlbHC%2FJVg5ST2AoHtph1XAsQL0bObX"

' String is too long to be typed in one line...
a1 = "%2FwEWdALpx6COCwKm07CqBwKSh%2B%2FQCgL96MW%2BBgLN6MW%2BBgLav7PDDQLCv%2FPADQLNv%2FPADQLcv%2FPADQLfv%2FPADQLev%2FPADQLZv%2FPADQLYv%2FPADQLbv%2FPADQLav%2FPADQLFv%2FPADQLduMOkAwLq0v%2FjCQLq0uO8AQLq0teZCgLq0rvyAwLq0q%2FPDALq0pOoBALq0oeFDQLq0uvhBgLq0p%2BJAwLq0oPiDALX%2B53NDwLX%2B4GmBwLX%2B%2FUCAtf72d8JAtf7zbgBAtf7sZUKAtf7pe4DAtf7icsMAtf7vfIJAtf7oc8CApOYyLkHApOYvBICk5ig7wkCk5iUyAICk5j4pAoCk5jsgQMCk5jQ2gwCk5jEtwQCk5jo3gICk5jcuwoC%2BKHuog0C%2BKHS%2FwYC%2BKHG2A8C%2BKGqtQcC%2BKGeDgL4oYLrCQL4ofbHAgL4odqgCgL4oY7ICAL4ofIkAuW2jIwDAuW28OgMAuW25MUFAsTR38AHAvO744cNAvO7%2F9gFAvO7y%2F0OAvO7p5YHAvO7s6sIAvO7j0wC87ub4QkC87v3hQIC87uD7QcC87ufhggCzpKBqQsCzpKdwgMCzpLp5gQCzpLFuw0CzpLR3AUCzpKt8Q4CzpK5igcCzpKVrwgCzpKhlg0CzpK9qwYCivHU3Q"
a2 = "MCivGg9gQCivG8iw0CivGIrAYCivHkwA4CivHw5QcCivHMvggCivHYUwKK8fS6BgKK8cDfDgLhyPLGCQLhyM6bAgLhyNq8CwLhyLbRAwLhyILqBALhyJ6PDQLhyOqjBgLhyMbEDgLhyJKsDALhyO7ABAL835DoBwL83%2ByMCAL83%2FihAQLnzLDSBAL4zLDSBAL5zLDSBAL6zLDSBAL8zLDSBAL9zLDSBAK3wpPeDgKFwpPeDgKuh8zbAwKhh8zbAwLR2eHwDAKFt7SHCcQGh8eHqGGqe%2F6U9Wz%2FpSk9FF8d"

RP2 = "&__EVENTVALIDATION=" & a1 & a2

' Query Parameters
QP1 = "&tbTicker=" & ticker
QP2 = "&ddBasis=Q"
QP3 = "&ddPeriod=0"
QP4 = "&ddFrom=" & CStr(Year(DateAdd("yyyy", -10, Date)))
QP5 = "&ddTo=" & CStr(Year(Date))
QP6 = "&ddFormType=0"

XMLPage.send RP1 & RP2 & QP1 & QP2 & QP3 & QP4 & QP5 & QP6

HTMLDoc.body.innerHTML = XMLPage.responseText

r = 1
c = 1
offset = 0 * shift

Sheets(SheetName).Select

Cells.Select
Selection.ClearContents

'Extract data from table
For Each HTMLRow In HTMLDoc.getElementsByTagName("tr")
    For Each HTMLCell In HTMLRow.getElementsByTagName("th")
        Cells(r, c + offset).value = HTMLCell.innerText
        c = c + 1
    Next HTMLCell
    For Each HTMLCell In HTMLRow.getElementsByTagName("td")
        Cells(r, c + offset).value = HTMLCell.innerText
        c = c + 1
    Next HTMLCell
c = 1
r = r + 1
Next HTMLRow

' Generate balance statements
'======================================
'Request
XMLPage.Open "Post", "https://nt3-s.zacks.com/fundamreports/Default.aspx", False

' Header
XMLPage.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

QP6 = "&ddFormType=1"

XMLPage.send RP1 & RP2 & QP1 & QP2 & QP3 & QP4 & QP5 & QP6

HTMLDoc.body.innerHTML = XMLPage.responseText

r = 1
c = 1
offset = 1 * shift

'Extract data from table
For Each HTMLRow In HTMLDoc.getElementsByTagName("tr")
    For Each HTMLCell In HTMLRow.getElementsByTagName("th")
        Cells(r, c + offset).value = HTMLCell.innerText
        c = c + 1
    Next HTMLCell
    For Each HTMLCell In HTMLRow.getElementsByTagName("td")
        Cells(r, c + offset).value = HTMLCell.innerText
        c = c + 1
    Next HTMLCell
c = 1
r = r + 1
Next HTMLRow

EDIT: I changed the code to include more details about my program. The sub will collect the income statements, balance sheets, cash flows, and other metrics for multiple companies at once. I included a couple of instances of how I'm using the POST method to parse the data.

A: By calculating with every iteration, add Application.Calculation = xlManual to the beginning of your macro and Application.Calculation = xlAutomatic to the end which will prevent updating calculations after every passing loop.


text:
Q: Finding roads with similar incline What I'm trying to do is find a road (or a portions of road) from one country that is similar to another road(or portion of a road) from a different country and the road property I'm comparing is relative changes in elevation.
For example, if I have a 100km road stretch in Kenya, looking at how the elevation changes every 1km, I would like to know if there is a either a continuous 100k road stretch in Namibia with very similar elevation changes or a smaller stretch (if the full length doesn't exist).
Since I have no prior GIS experience, I started using the Google Maps API in Javascript (and it's Elevation API), but I'm open to any suggestion.
At the moment I'm considering taking a possibly very naive approach:

*

*store input road data from country #1 as a 1 dimensional list of delta elevations (every 1km)

*index roads from country #2 as 1D lists of delta elevations

*(somehow) search for input road in the indexed road data. Either iterated through the indexed 2 lists and sort by the average difference between two sections or attempt 1D template matching ?

Is what I'm attempting achievable ?
Am I asking the right question (or I should look at comparing roads in a different way) ?
If so, is there an efficient/elegant solution to searching similar road areas based on relative elevation changes ?


text:
Q: Error on installing gem Nokogiri-1.8.4 OS: AMI 2018.03.0 (HVM)
Ruby version: 2.3.7p456 (2018-03-28 revision 63024) [x86_64-linux-gnu] - installed using yum install ruby23
gem install nokogiri throws:
Building native extensions.  This could take a while...
ERROR:  Error installing nokogiri:
ERROR: Failed to build gem native extension.

current directory: /home/ec2-user/.gem/ruby/2.3/gems/nokogiri-
1.8.4/ext/nokogiri
/usr/bin/ruby2.3 -r ./siteconf20180801-6218-101te4s.rb extconf.rb
mkmf.rb can't find header files for ruby at
/usr/share/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /home/ec2-
user/.gem/ruby/2.3/gems/nokogiri-1.8.4 for inspection.
Results logged to /home/ec2-user/.gem/ruby/2.3/extensions/x86_64-
linux/2.3/nokogiri-1.8.4/gem_make.out

what am i missing here?

A: From the error output, it would seem it can't find the development dependencies for Ruby, which Nokogiri is trying to use in order to build the gem natively.
You can run yum -y install gcc ruby-devel rubygems to make certain the dependencies are installed.
Basing my answer somewhat from https://stackoverflow.com/a/4502672/1129980
Update
Tested this now on a new EC2 instance:
yum install -y ruby23-devel gcc libxml2 libxml2-devel libxslt libxslt-devel patch
gem install nokogiri --no-ri --no-rdoc

That works :)

A: Try running the below mentioned commands
sudo yum -y install ruby-dev ( or ruby-devel)
sudo yum -y install libgmp-dev libgmpxx4ldbl ruby-dev ruby2.3-dev


text:
Q: Android SlidingDrawer how-to I've looked in many places, but I cant find a decent tutorial on how to make a SlidingDrawer for my application.
Say i already have an XML file, and i want to add a sliding drawer to it..i also want to add a textview and listview object, and some buttons in it...how would i go about doing that?
Any help will be greatly appreciated!

A: Here is a SlidingDrawer sample app. In particular, here is the layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#FF4444CC"
        >
    <SlidingDrawer
        android:id="@+id/drawer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:handle="@+id/handle"
        android:content="@+id/content">
        <ImageView
            android:id="@id/handle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/tray_handle_normal"
        />
        <Button
            android:id="@id/content"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="I'm in here!"
        />
    </SlidingDrawer>
</FrameLayout>

Now, in this case, the whole activity is just a SlidingDrawer. That's relatively unusual -- this sample is short because it is from a book.
More commonly, I would expect you to put a SlidingDrawer as a child of a RelativeLayout, so you can have other children of the RelativeLayout and have the drawer slide over top of them when opened. I believe you will need the SlidingDrawer to be the last child of the RelativeLayout in this case.


text:
Q: Index Match? Or some other function? 'Student Needs'! Columns I through O contain information on when each student attends an intervention class. Intervention classes take place during the second half of the classes (Science or social studies) or during the second half of Co-taught classes (math or ELA). Science and social studies interventions are done on either Monday/Wednesday or Tuesday/Friday (Thursdays have a special schedule that we do not need to consider). Math and ELA interventions occur on all four days.
In 'Student Master'!, each student's schedule is listed for both MW and TF. In Columns E, G, K, and M, I would like to populate any of the interventions that are listed in the 'Student Needs'! sheet. For instance, Lindsey Lukowski has Social Skills on MW2 (Mondays and Wednesdays 2nd hour).  So in cell 'Student Master'! G31 should return "Social Skills".
William Watters is getting Read Naturally and Reading Comp during his 5th Hour Co-Taught ELA. So 'Student Master'! K51 and K52 should both return Read Naturally & Reading Comp (in the same cell).
Here is the workbook:
https://docs.google.com/spreadsheets/d/1aW7ExATzMn9Rf8IFLI4v-CQiqsXnxyDm8PxqMW999bY/edit?usp=sharing

A: Here is a complex functions that seems to do what you want. I have tested it in a copy of your sheet
Just Change E$2 for different columns.
=IFERROR(INDIRECT("'Student Needs'!"&CHAR(72+IFERROR(MATCH("HR "&E$2,ARRAYFORMULA(REGEXEXTRACT(INDIRECT("'Student Needs'!I"&REGEXEXTRACT($A3,"[0-9]+")+5&":N"&REGEXEXTRACT($A3,"[0-9]+")+5),"[A-Z ]+[0-9]")),0),MATCH($C3,ARRAYFORMULA(REGEXEXTRACT(INDIRECT("'Student Needs'!I"&REGEXEXTRACT($A3,"[0-9]+")+5&":N"&REGEXEXTRACT($A3,"[0-9]+")+5),"[A-Z]+")),0)))&5))

Also I am not sure where "6- Science" should go? Is this also HR 6?

In order for it to work with actual
=IFERROR(INDIRECT("'Student Needs'!"&CHAR(72+IFERROR(MATCH("HR "&E$2,ARRAYFORMULA(REGEXEXTRACT(INDIRECT("'Student Needs'!I"&ROW(VLOOKUP($A3,'Student Needs'!$A$1:$B,2,false))&":N"&ROW(VLOOKUP($A3,'Student Needs'!$A$1:$B,2,false))),"[A-Z ]+[0-9]")),0),MATCH($C3,ARRAYFORMULA(REGEXEXTRACT(INDIRECT("'Student Needs'!I"&ROW(VLOOKUP($A3,'Student Needs'!$A$1:$B,2,false))&":N"&ROW(VLOOKUP($A3,'Student Needs'!$A$1:$B,2,false))),"[A-Z]+")),0)))&5))