subprocess.call
Automatically waits , you can also use:
p1.wait()
You need to set your window to be topmost.
When I look at this description, I have a feeling, that this xdr integer is just a big-endian "standard" integer, but it's expressed in the most obfuscated way. Two's complement notation is better know as U2, and it's what we are using on today's processors. The byte order indicates that it's a big-endian notation.
So, answering your question, you should inverse elements in your array (0 <--> 3, 1 <-->2), as they are encoded in little-endian. Just to make sure, you should first check BitConverter.IsLittleEndian
to see on what machine you are running.
In my case the issue was that the emulator was making a request to:
http://10.0.2.2:8081/debugger-ui
instead of:
http://localhost:8081/debugger-ui
and the request was failing.
To solve the issue: Before enabling remote debugging on your emulator, open http://localhost:8081/debugger-ui
in chrome. Then enable remote debugging and go back to the chrome page where you should see your console logs.
text = "42 0"
nums = [int(n) for n in text.split()]
This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.
In line number 4:
def ret(n):
if n > 9:
temp = "two digits"
return temp #Line 4
else:
temp = "one digit"
return temp #Line 8
print("return statement")
ret(10)
After the conditional statement gets executed the ret()
function gets terminated due to return temp
(line 4).
Thus the print("return statement")
does not get executed.
Output:
two digits
This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.
Returning Values
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.
To bring out the difference between print and return:
def ret(n):
if n > 9:
print("two digits")
return "two digits"
else :
print("one digit")
return "one digit"
ret(25)
Output:
two digits
'two digits'
For merging first branch to second one:
on first branch: git merge secondBranch
on second branch: Move to first branch-> git checkout firstBranch-> git merge secondBranch
Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax
with dataType: 'jsonp'
meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do
then jQuery will add ?callback={some_random_dynamically_generated_method}
.
This method is more kind of a proxy actually attached in window
object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Summary
Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.
If you have reqested with query string
?callback=my_callback_method
then, your server must response data wrapped like this:
my_callback_method({your json serialized data});
If you really don't want to use any server controls, you should put the Response.Write
in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
This is a simple loop that keeps prompting unless the user selects 'y' or 'n'
$confirmation = Read-Host "Ready? [y/n]"
while($confirmation -ne "y")
{
if ($confirmation -eq 'n') {exit}
$confirmation = Read-Host "Ready? [y/n]"
}
I had the same problem and to solve this I follow this blog article: http://www.mkyong.com/java/how-to-set-java_home-environment-variable-on-mac-os-x/
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
$ source .bash_profile
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
special tks to @mkyong
The new urllib3 library has a nice documentation here
In order to get your desired result you shuld follow that:
Import urllib3
from bs4 import BeautifulSoup
url = 'http://www.thefamouspeople.com/singers.php'
http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data.decode('utf-8'))
The "decode utf-8" part is optional. It worked without it when i tried, but i posted the option anyway.
Source: User Guide
What do you want to do with the attribute? Is it an html attribute or something of your own?
Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo"
will do it.
For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo
and subsequently read it without issue.
Be aware that a lot of the really killer features are only in Enterprise Edition. Data compression and backup compression are among two of my top favorites - they give you free performance improvements right off the bat. Data compression lessens the amount of I/O you have to do, so a lot of queries speed up 20-40%. CPU use goes up, but in today's multi-core environments, we often have more CPU power but not more IO. Anyway, those are only in Enterprise.
If you're only going to use Standard Edition, then most of the improvements require changes to your application code and T-SQL code, so it's not quite as easy of a sell.
If you add file ipython_config.py into the ~/.ipython/profile_default directory with lines like below, then the autoreload functionality will be loaded on IPython startup (tested on 2.0.0):
print "--------->>>>>>>> ENABLE AUTORELOAD <<<<<<<<<------------"
c = get_config()
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
'use strict'
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
For better understanding run the above code and compare the results..
You could run it without the -jar
command line argument if you happen to know the name of the main class you wish to run:
java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass
If perchance you are using linux, you should use ":" instead of ";" in the classpath.
You can add any paths you want to the hashtable of your bash:
hash -d <CustomName>=<RealPath>
Now you will be able to cd ~<CustomName>
. To make it permanent add it to your bashrc script.
Notice that this hashtable is meant to provide a cache for bash not to need to search for content everytime a command is executed, therefore this table will be cleared on events that invalidate the cache, e.g. modifying $PATH
.
For people using Tomee or Tomcat and can't get it working, try to create context.xml in META-INF and add allowCasualMultipartParsing="true"
<?xml version="1.0" encoding="UTF-8"?>
<Context allowCasualMultipartParsing="true">
<!-- empty or not depending your project -->
</Context>
Operator? NO, but I think you can change your culture so that string comparison is not case-sensitive.
// you'll want to change this...
System.Threading.Thread.CurrentThread.CurrentCulture
// and you'll want to custimize this
System.Globalization.CultureInfo.CompareInfo
I'm confident that it will change the way that strings are being compared by the equals operator.
In my case.. following steps resolved:
There was a column value which was set to "Update" - replaced it with Edit (non sql keyword) There was a space in one of the column names (removed the extra space or trim)
I know it's a late answer but I had the same problem and my solution was just adding implementation 'com.android.support:design:28.0.0
or any above support design libraries !!
You may like lfqueue, https://github.com/Taymindis/lfqueue. It’s lock free concurrent queue. I’m currently using it to consuming the queue from multiple incoming calls and works like a charm.
You can use Explicit wait or Fluent Wait
Example of Explicit Wait -
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));
Example of Fluent Wait -
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(20, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("about_me"));
}
});
Check this TUTORIAL for more details.
I would suggest:
function onChange(field){
field.old=field.recent;
field.recent=field.value;
//we have available old value here;
}
Update: MVC 3 and newer versions have built-in support for this. See JohnnyO's highly upvoted answer below for recommended solutions.
I do not think there are any immediate helpers for achieving this, but I do have two ideas for you to try:
// 1: pass dictionary instead of anonymous object
<%= Html.ActionLink( "back", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new Dictionary<string,Object> { {"class","prev"}, {"data-details","yada"} } )%>
// 2: pass custom type decorated with descriptor attributes
public class CustomArgs
{
public CustomArgs( string className, string dataDetails ) { ... }
[DisplayName("class")]
public string Class { get; set; }
[DisplayName("data-details")]
public string DataDetails { get; set; }
}
<%= Html.ActionLink( "back", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new CustomArgs( "prev", "yada" ) )%>
Just ideas, haven't tested it.
You can try to turn support on in spring's converter
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// add converter suport Content-Type: 'application/x-www-form-urlencoded'
converters.stream()
.filter(AllEncompassingFormHttpMessageConverter.class::isInstance)
.map(AllEncompassingFormHttpMessageConverter.class::cast)
.findFirst()
.ifPresent(converter -> converter.addSupportedMediaTypes(MediaType.APPLICATION_FORM_URLENCODED_VALUE));
}
}
I like simbu's approach, but I ain't comfortable to use first-child or last-child. Instead I only modify the content of a repeating list-comma class.
.list-comma + .list-comma::before {
content: ', ';
}
<span class="list-comma" ng-repeat="destination in destinations">
{{destination.name}}
</span>
and take a look at the getopt module. It works quite good for me!
Use http://us1.php.net/parse_str
Attention, it's usage is:
parse_str($str, &$array);
not
$array = parse_str($str);
After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:
PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2
Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.
[c] * n
can be written as:
Array(n+1).join(1).split('').map(function(){return c;})
so for [2] * 5
Array(6).join(1).split('').map(function(){return 2;})
Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html
CheckBox: use change event to call the function and pass the event.
<label class="container">
<input type="checkbox" [(ngModel)]="theCheckbox" data-md-icheck
(change)="toggleVisibility($event)"/>
Checkbox is <span *ngIf="marked">checked</span><span
*ngIf="!marked">unchecked</span>
<span class="checkmark"></span>
</label>
<div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>
A simple AJAX call to your server, and then the serverside logic to get the ip address should do the trick.
$.getJSON('getip.php', function(data){
alert('Your ip is: ' + data.ip);
});
Then in php you might do:
<?php
/* getip.php */
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
print json_encode(array('ip' => $ip));
I think you add click event five times. Try to count how many times you do this.
console.log('add click event')
$(".addproduct").click(function(){ });
Here is my approach, including some helper methods
export default class Enum {
constructor(name){
this.name = name;
}
static get values(){
return Object.values(this);
}
static forName(name){
for(var enumValue of this.values){
if(enumValue.name === name){
return enumValue;
}
}
throw new Error('Unknown value "' + name + '"');
}
toString(){
return this.name;
}
}
-
import Enum from './enum.js';
export default class ColumnType extends Enum {
constructor(name, clazz){
super(name);
this.associatedClass = clazz;
}
}
ColumnType.Integer = new ColumnType('Integer', Number);
ColumnType.Double = new ColumnType('Double', Number);
ColumnType.String = new ColumnType('String', String);
I admit that I have never used any advanced math in programming except in some pet projects that are about math topics.
That said, I do enjoy to working together with people that are bright enough to grok maths. Mastering complex and difficult stuff helps to get your brain into shape to solve complex and difficult programming problems.
I was also a bit confused between adjustResize and adjustPan when I was a beginner. The definitions given above are correct.
AdjustResize : Main activity's content is resized to make room for soft input i.e keyboard
AdjustPan : Instead of resizing overall contents of the window, it only pans the content so that the user can always see what is he typing
AdjustNothing : As the name suggests nothing is resized or panned. Keyboard is opened as it is irrespective of whether it is hiding the contents or not.
I have a created a example for better understanding
Below is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Type Here"
app:layout_constraintTop_toBottomOf="@id/button1"/>
<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/button2"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginBottom="@dimen/margin70dp"/>
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="@id/button1"
app:layout_constraintEnd_toStartOf="@id/button3"
android:layout_marginBottom="@dimen/margin70dp"/>
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button3"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/button2"
android:layout_marginBottom="@dimen/margin70dp"/>
</android.support.constraint.ConstraintLayout>
Here is the design view of the xml
AdjustResize Example below:
AdjustPan Example below:
AdjustNothing Example below:
There are different Names of SD-Cards.
This Code check every possible Name (I don't guarantee that these are all names but the most are included)
It prefers the main storage.
private String SDPath() {
String sdcardpath = "";
//Datas
if (new File("/data/sdext4/").exists() && new File("/data/sdext4/").canRead()){
sdcardpath = "/data/sdext4/";
}
if (new File("/data/sdext3/").exists() && new File("/data/sdext3/").canRead()){
sdcardpath = "/data/sdext3/";
}
if (new File("/data/sdext2/").exists() && new File("/data/sdext2/").canRead()){
sdcardpath = "/data/sdext2/";
}
if (new File("/data/sdext1/").exists() && new File("/data/sdext1/").canRead()){
sdcardpath = "/data/sdext1/";
}
if (new File("/data/sdext/").exists() && new File("/data/sdext/").canRead()){
sdcardpath = "/data/sdext/";
}
//MNTS
if (new File("mnt/sdcard/external_sd/").exists() && new File("mnt/sdcard/external_sd/").canRead()){
sdcardpath = "mnt/sdcard/external_sd/";
}
if (new File("mnt/extsdcard/").exists() && new File("mnt/extsdcard/").canRead()){
sdcardpath = "mnt/extsdcard/";
}
if (new File("mnt/external_sd/").exists() && new File("mnt/external_sd/").canRead()){
sdcardpath = "mnt/external_sd/";
}
if (new File("mnt/emmc/").exists() && new File("mnt/emmc/").canRead()){
sdcardpath = "mnt/emmc/";
}
if (new File("mnt/sdcard0/").exists() && new File("mnt/sdcard0/").canRead()){
sdcardpath = "mnt/sdcard0/";
}
if (new File("mnt/sdcard1/").exists() && new File("mnt/sdcard1/").canRead()){
sdcardpath = "mnt/sdcard1/";
}
if (new File("mnt/sdcard/").exists() && new File("mnt/sdcard/").canRead()){
sdcardpath = "mnt/sdcard/";
}
//Storages
if (new File("/storage/removable/sdcard1/").exists() && new File("/storage/removable/sdcard1/").canRead()){
sdcardpath = "/storage/removable/sdcard1/";
}
if (new File("/storage/external_SD/").exists() && new File("/storage/external_SD/").canRead()){
sdcardpath = "/storage/external_SD/";
}
if (new File("/storage/ext_sd/").exists() && new File("/storage/ext_sd/").canRead()){
sdcardpath = "/storage/ext_sd/";
}
if (new File("/storage/sdcard1/").exists() && new File("/storage/sdcard1/").canRead()){
sdcardpath = "/storage/sdcard1/";
}
if (new File("/storage/sdcard0/").exists() && new File("/storage/sdcard0/").canRead()){
sdcardpath = "/storage/sdcard0/";
}
if (new File("/storage/sdcard/").exists() && new File("/storage/sdcard/").canRead()){
sdcardpath = "/storage/sdcard/";
}
if (sdcardpath.contentEquals("")){
sdcardpath = Environment.getExternalStorageDirectory().getAbsolutePath();
}
Log.v("SDFinder","Path: " + sdcardpath);
return sdcardpath;
}
Maybe these answers above are old but with the new Android Studios 1, you do the following to see the module to run on 1.7 (or 1.6 if you prefer). Click File --> Project Structure. Select the module you want to run and then under "Source Compatibility" and "Target Compatibility", select 1.7. Click "OK".
You are looking for the greatest common divisor (GCD).
You can calculate it recursively in VBA, like this:
Function GCD(numerator As Integer, denominator As Integer)
If denominator = 0 Then
GCD = numerator
Else
GCD = GCD(denominator, numerator Mod denominator)
End If
End Function
And use it in your sheet like this:
ColumnA ColumnB ColumnC
1 33 11 =A1/GCD(A1; B1) & ":" & B1/GCD(A1; B1)
2 25 5 =A2/GCD(A2; B2) & ":" & B2/GCD(A2; B2)
It is recommendable to store the result of the function call in a hidden column and use this result to avoid calling the function twice per row:
ColumnA ColumnB ColumnC ColumnD
1 33 11 =GCD(A1; B1) =A1/C1 & ":" & B1/C1
2 25 5 =GCD(A2; B2) =A2/C2 & ":" & B2/C2
You can't do this reliably across all browsers. Microsoft no longer supports DX filters as of IE10+, so none of the solutions here work fully:
https://msdn.microsoft.com/en-us/library/hh801215(v=vs.85).aspx
The only property that works reliably across all browsers is box-shadow
, and this just puts the border on your element (e.g. a div), resulting in a square border:
box-shadow: horizontalOffset verticalOffset blurDistance spreadDistance color inset;
e.g.
box-shadow: -2px 6px 12px 6px #CCCED0;
If you happen to have an image that is 'square' but with uniform rounded corners, the drop shadow works with border-radius
, so you could always emulate the rounded corners of your image in your div.
Here's the Microsoft documentation for box-shadow
:
https://msdn.microsoft.com/en-us/library/gg589484(v=vs.85).aspx
No need for array. Just use something like this:
Sub ARRAYER()
Dim Rng As Range
Dim Number_of_Sims As Long
Dim i As Long
Number_of_Sims = 10
Set Rng = Range("C4:G4")
For i = 1 To Number_of_Sims
Rng.Offset(i, 0).Value = Rng.Value
Worksheets("Sheetname").Calculate 'replacing Sheetname with name of your sheet
Next
End Sub
col-lg-4 col-md-6 col-sm-8 col-11 mx-auto
1. col-lg-4 = 1200px (popular 1366, 1600, 1920+)
2. col-md-6 = 970px (popular 1024, 1200)
3. col-sm-8 = 768px (popular 800, 768)
4. col-11 set default smaller devices for gutter (popular 600,480,414,375,360,312)
5. mx-auto = always block center
The typed way to do this would be:
Number(true) // 1
Number(false) // 0
Without any third-party tools and any app, you can find unused CSS and javascript by using chrome dev tools in the coverage tab. read the post below from google developers. chrome coverage tab
I had the same problem. It seems that the unobtrusive validation scripts were not loaded (see screenshot at the end). I fixed it by adding at the end of _Layout.cshtml
@Scripts.Render("~/bundles/jqueryval")
The end result:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@RenderSection("scripts", required: false)
Except for my pretty standard CRUD views everything is Visual studio project template defaults.
Loaded scripts after fixing the problem:
I have created a filter. The filter can be used in any page.
Vue.filter('toCurrency', function (value) {
if (typeof value !== "number") {
return value;
}
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0
});
return formatter.format(value);
});
Then I can use this filter like this:
<td class="text-right">
{{ invoice.fees | toCurrency }}
</td>
I used these related answers to help with the implementation of the filter:
If you want to print multiple rows, you can iterate through the result by using a cursor. e.g. print all names from sys.database_principals
DECLARE @name nvarchar(128)
DECLARE cur CURSOR FOR
SELECT name FROM sys.database_principals
OPEN cur
FETCH NEXT FROM cur INTO @name;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @name
FETCH NEXT FROM cur INTO @name;
END
CLOSE cur;
DEALLOCATE cur;
Use jQuery....I know you say you're trying to teach someone javascript, but teach him a cleaner technique... for instance, I could:
<select id="navigation">
<option value="unit_01.htm">Unit 1</option>
<option value="#5.2">Bookmark 2</option>
</select>
And with a little jQuery, you could do:
$("#navigation").change(function()
{
document.location.href = $(this).val();
});
Unobtrusive, and with clean separation of logic and UI.
JPA doesn't provide any specification on mapping annotations to select fetch strategy. In general, related entities can be fetched in any one of the ways given below
So SELECT
and JOIN
are two extremes and SUBSELECT
falls in between. One can choose suitable strategy based on her/his domain model.
By default SELECT
is used by both JPA/EclipseLink and Hibernate. This can be overridden by using:
@Fetch(FetchMode.JOIN)
@Fetch(FetchMode.SUBSELECT)
in Hibernate. It also allows to set SELECT
mode explicitly using @Fetch(FetchMode.SELECT)
which can be tuned by using batch size e.g. @BatchSize(size=10)
.
Corresponding annotations in EclipseLink are:
@JoinFetch
@BatchFetch
Please take a look here:
1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.
2) Step-by-step tutorial how to use serial ports on windows
3) You can use this literally on MinGW
Here's some very, very simple code (without any error handling or settings):
#include <windows.h>
/* ... */
// Open serial port
HANDLE serialHandle;
serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(serialHandle, &timeout);
Now you can use WriteFile()
/ ReadFile()
to write / read bytes.
Don't forget to close your connection:
CloseHandle(serialHandle);
You can use below code to find out principal (user email who logged in)
org.opensaml.saml2.core.impl.NameIDImpl principal =
(NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String email = principal.getValue();
This code is written on top of SAML.
It's been a few good days with node, and you're right to say that you can't create a webserver without gzip.
There are quite a lot options given on the modules page on the Node.js Wiki. I tried out most of them, but this is the one which I'm finally using -
https://github.com/donnerjack13589/node.gzip
v1.0 is also out and it has been quite stable so far.
Generator based line reader: https://github.com/neurosnap/gen-readlines
var fs = require('fs');
var readlines = require('gen-readlines');
fs.open('./file.txt', 'r', function(err, fd) {
if (err) throw err;
fs.fstat(fd, function(err, stats) {
if (err) throw err;
for (var line of readlines(fd, stats.size)) {
console.log(line.toString());
}
});
});
Could you show us what your title
actually is? When I submit
<!DOCTYPE html>
<html>
<title>Dolce & Gabbana</title>
<body>
<p>am i allowed loose & mpersands?</p>
</body>
</html>
to http://validator.w3.org/ - explicitly asking it to use the experimental HTML 5 mode - it has no complaints about the &
s...
If you want to focus on each letter
you can do like that, I refer to this question
function truncate(source, size) {_x000D_
return source.length > size ? source.slice(0, size - 1) + "…" : source;_x000D_
}_x000D_
_x000D_
var text = truncate('Truncate text to fit in 3 lines', 14);_x000D_
console.log(text);
_x000D_
If you want to focus on each word
you can do like that + space
const truncate = (title, limit = 14) => { // 14 IS DEFAULT ARGUMENT _x000D_
const newTitle = [];_x000D_
if (title.length > limit) {_x000D_
title.split(' ').reduce((acc, cur) => {_x000D_
if (acc + cur.length <= limit) {_x000D_
newTitle.push(cur);_x000D_
}_x000D_
return acc + cur.length;_x000D_
}, 0);_x000D_
_x000D_
return newTitle.join(' ') + '...'_x000D_
}_x000D_
return title;_x000D_
}_x000D_
_x000D_
var text = truncate('Truncate text to fit in 3 lines', 14);_x000D_
console.log(text);
_x000D_
If you want to focus on each word
you can do like that + without space
const truncate = (title, limit = 14) => { // 14 IS DEFAULT ARGUMENT _x000D_
const newTitle = [];_x000D_
if (title.length > limit) {_x000D_
Array.prototype.slice.call(title).reduce((acc, cur) => {_x000D_
if (acc + cur.length <= limit) {_x000D_
newTitle.push(cur);_x000D_
}_x000D_
return acc + cur.length;_x000D_
}, 0);_x000D_
_x000D_
return newTitle.join('') + '...'_x000D_
}_x000D_
return title;_x000D_
}_x000D_
_x000D_
var text = truncate('Truncate text to fit in 3 lines', 14);_x000D_
console.log(text);
_x000D_
Set alignment: Alignment.centerRight
in Container:
Container(
alignment: Alignment.centerRight,
child:Text(
"Hello",
),
)
To further compliment Andrés Torres Marroquín and Leo Dabus, I have a version that preserves fractional seconds. I can't find it documented anywhere, but Apple truncate fractional seconds to the microsecond (3 digits of precision) on both input and output (even though specified using SSSSSSS, contrary to Unicode tr35-31).
I should stress that this is probably not necessary for most use cases. Dates online do not typically need millisecond precision, and when they do, it is often better to use a different data format. But sometimes one must interoperate with a pre-existing system in a particular way.
Xcode 8/9 and Swift 3.0-3.2
extension Date {
struct Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXXXX"
return formatter
}()
}
var iso8601: String {
// create base Date format
var formatted = DateFormatter.iso8601.string(from: self)
// Apple returns millisecond precision. find the range of the decimal portion
if let fractionStart = formatted.range(of: "."),
let fractionEnd = formatted.index(fractionStart.lowerBound, offsetBy: 7, limitedBy: formatted.endIndex) {
let fractionRange = fractionStart.lowerBound..<fractionEnd
// replace the decimal range with our own 6 digit fraction output
let microseconds = self.timeIntervalSince1970 - floor(self.timeIntervalSince1970)
var microsecondsStr = String(format: "%.06f", microseconds)
microsecondsStr.remove(at: microsecondsStr.startIndex)
formatted.replaceSubrange(fractionRange, with: microsecondsStr)
}
return formatted
}
}
extension String {
var dateFromISO8601: Date? {
guard let parsedDate = Date.Formatter.iso8601.date(from: self) else {
return nil
}
var preliminaryDate = Date(timeIntervalSinceReferenceDate: floor(parsedDate.timeIntervalSinceReferenceDate))
if let fractionStart = self.range(of: "."),
let fractionEnd = self.index(fractionStart.lowerBound, offsetBy: 7, limitedBy: self.endIndex) {
let fractionRange = fractionStart.lowerBound..<fractionEnd
let fractionStr = self.substring(with: fractionRange)
if var fraction = Double(fractionStr) {
fraction = Double(floor(1000000*fraction)/1000000)
preliminaryDate.addTimeInterval(fraction)
}
}
return preliminaryDate
}
}
Simple:
let objCopy = JSON.parse(JSON.stringify(obj));
This Also Works (Only for Arrays)
let objCopy2 = obj.slice()
ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE Serde worked for me. My delimiter was '|' and one of the columns is enclosed in double quotes.
Query:
CREATE EXTERNAL TABLE EMAIL(MESSAGE_ID STRING, TEXT STRING, TO_ADDRS STRING, FROM_ADDRS STRING, SUBJECT STRING, DATE STRING)
ROW FORMAT SERDE 'ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE'
WITH SERDEPROPERTIES (
"SEPARATORCHAR" = "|",
"QUOTECHAR" = "\"",
"ESCAPECHAR" = "\""
)
STORED AS TEXTFILE location '/user/abc/csv_folder';
<%: DateTime.Today.ToShortDateString() %>
Usually you already know the extension, so you might wish to use:
basename filename .extension
for example:
basename /path/to/dir/filename.txt .txt
and we get
filename
This works in browser and nodejs Live browser demo
const cpFetch= require('cp-fetch');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s';
const chain = cpFetch(url, {timeout: 10000})
.then(response => response.json())
.then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))
setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms
As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.
So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:
Sub MasterMacro()
Call Macro1
Call Macro2
Call Macro3
Call Macro4
End Sub
Give ID
and attribute runat='server'
as :
<div class="tab-pane active" id="portlet_tab1" runat="server">
//somecode Codebehind:
Access at code behind
Control Test = Page.FindControl("portlet_tab1");
Test.Style.Add("display", "none");
or
portlet_tab1.Style.Add("display", "none");
A little note to the SeanJA answer.
Interestingly, if you use KnockoutJS and jQuery together the following inputs with different IDs, but with the same data-bind observable:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: first_dt" id="date_2" class="datepick" />
will bind one (the same) datepicker to both of the inputs (even though they have different ids or names).
Use separate observables in your ViewModel to bind a separate datepicker to each input:
<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: second_dt" id="date_2" class="datepick" />
Initialization:
$('.datepick').each(function(){
$(this).datepicker();
});
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).
The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)
From your other posts, I guess you want to learn a new language to get new skills. My advice is that the language is not really important, what is important is the quality of its community (advice, but also existing code you can read and learn from) and the available libraries/frameworks. In this respect, I think the "C family" is not the best choice for you: web libraries and frameworks are few, not portable and not great, and coding style of code you can study varies a lot and may confuse you a lot (although C is my favorite language).
I would advise to just learn C, and try to really understand the concept of pointers, then move to other languages more adapted to the web (Python or JavaScript comes to mind - or even Java). Also, in the C family, Objective-C has the best mix of power and simplicity in my opinion, but is a niche player.
I think you did like this:
<asp:Content ID="Content2" ContentPlaceHolderID="MasterContent" runat="server">
<form id="form1" runat="server">
</form>
</asp:Content>
The form tag isn't needed. because you already have the same tag in the master page.
So you just remove that and it should be working.
Please try this code:-
$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo "$result";
Here's a simple trap that prints the last argument of whatever failed to STDERR, reports the line it failed on, and exits the script with the line number as the exit code. Note these are not always great ideas, but this demonstrates some creative application you could build on.
trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
I put that in a script with a loop to test it. I just check for a hit on some random numbers; you might use actual tests. If I need to bail, I call false (which triggers the trap) with the message I want to throw.
For elaborated functionality, have the trap call a processing function. You can always use a case statement on your arg ($_) if you need to do more cleanup, etc. Assign to a var for a little syntactic sugar -
trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
throw=false
raise=false
while :
do x=$(( $RANDOM % 10 ))
case "$x" in
0) $throw "DIVISION BY ZERO" ;;
3) $raise "MAGIC NUMBER" ;;
*) echo got $x ;;
esac
done
Sample output:
# bash tst
got 2
got 8
DIVISION BY ZERO at 6
# echo $?
6
Obviously, you could
runTest1 "Test1 fails" # message not used if it succeeds
Lots of room for design improvement.
The draw backs include the fact that false
isn't pretty (thus the sugar), and other things tripping the trap might look a little stupid. Still, I like this method.
I just ran into this problem and the actual issue was that I forgot to add a proper application/json header before spitting out the actual JSON data.
header('Content-Type: application/json');
Try this script to get your browser language
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
Cheers
export default
affects the syntax when importing the exported "thing", when allowing to import, whatever has been exported, by choosing the name in the import
itself, no matter what was the name when it was exported, simply because it's marked as the "default".
A useful use case, which I like (and use), is allowing to export an anonymous function without explicitly having to name it, and only when that function is imported, it must be given a name:
default
:export function divide( x ){
return x / 2;
}
// only one 'default' function may be exported and the rest (above) must be named
export default function( x ){ // <---- declared as a default function
return x * x;
}
default
one:// The default function should be the first to import (and named whatever)
import square, {divide} from './module_1.js'; // I named the default "square"
console.log( square(2), divide(2) ); // 4, 1
When the {}
syntax is used to import a function (or variable) it means that whatever is imported was already named when exported, so one must import it by the exact same name, or else the import wouldn't work.
The default function must be first to import
import {divide}, square from './module_1.js
divide_1
was not exported in module_1.js
, thus nothing will be imported
import {divide_1} from './module_1.js
square
was not exported in module_1.js
, because {}
tells the engine to explicitly search for named exports only.
import {square} from './module_1.js
You probably want ANSI color codes. Most *nix terminals support them.
<!DOCTYPE html>
<html>
<head>
<style>
.block-system-branding-block {
flex: 0 1 40%;
}
@media screen and (min-width: 48em) {
.block-system-branding-block {
flex: 0 1 420px;
margin: 2.5rem 0;
text-align: left;
}
}
.flex-containerrow {
display: flex;
}
.flex-containerrow > div {
justify-content: center;
align-items: center;
}
.flex-containercolumn {
display: flex;
flex-direction: column;
}
.flex-containercolumn > div {
width: 300px;
margin: 10px;
text-align: left;
line-height: 20px;
font-size: 16px;
}
.flex-containercolumn > site-slogan {font-size: 12px;}
.flex-containercolumn > div > span{ font-size: 12px;}
</style>
</head>
<body>
<div id="block-umami-branding" class="block-system block-
system-branding-block">
<div class="flex-containerrow">
<div>
<a href="/" rel="home" class="site-logo">
<img src="https://placehold.it/120x120" alt="Home">
</a>
</div><div class="flex-containerrow"><div class="flex-containercolumn">
<div class="site-name ">
<a href="/" title="Home" rel="home">This is my sitename</a>
</div>
<div class="site-slogan "><span>Department of Test | Ministry of Test |
TGoII</span></div>
</div></div>
</div>
</div>
</body>
</html>
So as to have another possibility1 to find the files that are executable by the current user:
find . -type f -exec test -x {} \; -print
(the test command here is the one found in PATH, very likely /usr/bin/test
, not the builtin).
1 Only use this if the -executable
flag of find
is not available! this is subtly different from the -perm +111
solution.
>>> any([False, False, False])
False
>>> any([False, True, False])
True
>>> all([False, True, True])
False
>>> all([True, True, True])
True
The simple option to use with aggregate
is the length
function which will give you the length of the vector in the subset. Sometimes a little more robust is to use function(x) sum( !is.na(x) )
.
For me, a hint to wrap the troubled element in another HTML tag helped. However I also needed to add a key to that HTML tag. For example:
// Didn't work
<div>
<TroubledComponent/>
</div>
// Worked
<div key='uniqueKey'>
<TroubledComponent/>
</div>
sp_change_users_login
is deprecated.
Much easier is:
ALTER USER usr1 WITH LOGIN = login1;
I fixed this by making sure that that OpenSSL was installed on my machine and then adding this to my php.ini:
openssl.cafile=/usr/local/etc/openssl/cert.pem
I tried this (and worked for me):
var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(\'' + img + '\')';
ES6 syntax:
let img = 'data:image/png;base64, ...'
document.body.style.backgroundImage = `url('${img}')`
A bit better:
let setBackground = src => {
this.style.backgroundImage = `url('${src}')`
};
let node = nodeIGotFromDOM, img = imageBase64EncodedFromMyGF;
setBackground.call(node, img);
One additional reason to add final to parameter declarations is that it helps to identify variables that need to be renamed as part of a "Extract Method" refactoring. I have found that adding final to each parameter prior to starting a large method refactoring quickly tells me if there are any issues I need to address before continuing.
However, I generally remove them as superfluous at the end of the refactoring.
Extend LinearLayout/RelativeLayout and use it straight on the XML
package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
Paint paint;
public LinearLayoutOutlined(Context context) {
super(context);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
public LinearLayoutOutlined(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
setWillNotDraw(false) ;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
/*
Paint fillPaint = paint;
fillPaint.setARGB(255, 0, 255, 0);
fillPaint.setStyle(Paint.Style.FILL);
canvas.drawPaint(fillPaint) ;
*/
Paint strokePaint = paint;
strokePaint.setARGB(255, 255, 0, 0);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setStrokeWidth(2);
Rect r = canvas.getClipBounds() ;
Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
canvas.drawRect(outline, strokePaint) ;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.pkg_name.LinearLayoutOutlined
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=...
android:layout_height=...
>
... your widgets here ...
</com.pkg_name.LinearLayoutOutlined>
If you are making cross domain call the Use Jsonp. else the error is not returned.
Download it from here and extract LatoOFL.rar
then go to TTF and open this font-face-generator click at Choose File
choose font which you want to use and click at generate then download it and then go html
file open it and you see the code like this
@font-face {
font-family: "Lato Black";
src: url('698242188-Lato-Bla.eot');
src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
url('698242188-Lato-Bla.woff') format('woff'),
url('698242188-Lato-Bla.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
body{
font-family: "Lato Black";
direction: ltr;
}
change the src code and give the url where your this font directory placed, now you can use it at your website...
If you don't want to download it use this
<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />
Is this what you are wanting?
<body>_x000D_
<div id="div1" style="height: 500px;">_x000D_
<div id="div2" style="height: inherit; overflow: auto; border:1px solid red;">_x000D_
<div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
You can use
LEFT(column, length)
or
SUBSTRING(column, start index, length)
You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:
class Dictlist(dict):
def __setitem__(self, key, value):
try:
self[key]
except KeyError:
super(Dictlist, self).__setitem__(key, [])
self[key].append(value)
Output example:
>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}
If you haven't pushed your changes yet use git reset --soft [Hash for one commit]
to rollback to a specific commit. --soft
tells git to keep the changes being rolled back (i.e., mark the files as modified). --hard
tells git to delete the changes being rolled back.
One thing you should look into is the SQLite date and time functions, especially if you're going to have to manipulate a lot of dates. It's the sane way to use dates, at the cost of changing the internal format (has to be ISO, i.e. yyyy-MM-dd).
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
Use white-space:nowrap
and overflow:hidden
I'd make something like this:
var request = []
while(count<10){
request.push(db.getUser(email).then(function(res) { return res; }));
count++
};
Promise.all(request).then((dataAll)=>{
for (var i = 0; i < dataAll.length; i++) {
logger.log(dataAll[i]);
}
});
in this way, dataAll is an ordered array of all element to log. And log operation will perform when all promises are done.
I found this;
from here;
vba- Can a combobox present more then one column on it's textbox part?
and this may help;
I added a sort of demo here;
The general idea behind creating "optional arguments" is to first define an intermediate command that scans ahead to detect what characters are coming up next in the token stream and then inserts the relevant macros to process the argument(s) coming up as appropriate. This can be quite tedious (although not difficult) using generic TeX programming. LaTeX's \@ifnextchar
is quite useful for such things.
The best answer for your question is to use the new xparse
package. It is part of the LaTeX3 programming suite and contains extensive features for defining commands with quite arbitrary optional arguments.
In your example you have a \sec
macro that either takes one or two braced arguments. This would be implemented using xparse
with the following:
\documentclass{article} \usepackage{xparse} \begin{document} \DeclareDocumentCommand\sec{ m g }{% {#1% \IfNoValueF {#2} { and #2}% }% } (\sec{Hello}) (\sec{Hello}{Hi}) \end{document}
The argument { m g }
defines the arguments of \sec
; m
means "mandatory argument" and g
is "optional braced argument". \IfNoValue(T)(F)
can then be used to check whether the second argument was indeed present or not. See the documentation for the other types of optional arguments that are allowed.
Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global
, nonlocal
, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.
Here are some examples regarding global
:-
>>> global_var = 5
>>> def fn():
... print(global_var)
...
>>> fn()
5
>>> def fn_2():
... global_var += 2
... print(global_var)
...
>>> fn_2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
... global global_var
... global_var += 2
... print(global_var)
...
>>> fn_3()
7
The same patterns can be applied to nonlocal
variables too, but this keyword is only available to the latter Python versions.
In case you're wondering, nonlocal
is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def
within a def
, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...
Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner def
s using the same variable names as the outer ones, which just should just be avoided to be honest.
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call. Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'. Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
What, hang on?! ... Okay ya, maybe this makes more sense to someones else too.
[nodejs 7 mind you]
fs = import('fs');
let dirCont = fs.readdirSync( dir );
let files = dirCont.filter( function( elm ) {return elm.match(/.*\.(htm?html)/ig);});
Do whatever with regex make it an argument you set in the function with a default etc.
Or you can use like this. This may be faster.
int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
{
iRowIndex = i;
break;
}
if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
{
iRowIndex = j;
break;
}
j--;
}
if (iRowIndex != -1)
MessageBox.Show("Index is " + iRowIndex.ToString());
else
MessageBox.Show("Index not found." );
In Swift 5, you can utilize dot notation for a bit quicker syntax:
myButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
Otherwise, you'll use:
myButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
This worked for me in Swift 3
let time1 = 8.23
let time2 = 3.42
// Delay 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
print("Sum of times: \(time1 + time2)")
}
Simplest approach if the code is already tracked by Git then set new repository as your "origin" to push to.
cd existing-project
git remote set-url origin https://clone-url.git
git push -u origin --all
git push origin --tags
try white-space:normal;
This will override inheriting white-space:nowrap;
Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.
$scope.sortMyData = function (a, b)
{
var retVal = 0, key;
for (var i = 0; i < $scope.sortKeys.length; i++)
{
if (retVal !== 0)
{
break;
}
else
{
key = $scope.sortKeys[i];
if ('asc' === key.direction)
{
retVal = (a[key.field] < b[key.field]) ? -1 : (a[key.field] > b[key.field]) ? 1 : 0;
}
else
{
retVal = (a[key.field] < b[key.field]) ? 1 : (a[key.field] > b[key.field]) ? -1 : 0;
}
}
}
return retVal;
};
For vue-cli 3 open package.json
and under section eslintConfig
put no-console
under rules
and restart dev server (npm run serve
or yarn serve
)
...
"eslintConfig": {
...
"rules": {
"no-console": "off"
},
...
An alternative to converting the image is to create an RGB index from the palette.
from PIL import Image
def chunk(seq, size, groupByList=True):
"""Returns list of lists/tuples broken up by size input"""
func = tuple
if groupByList:
func = list
return [func(seq[i:i + size]) for i in range(0, len(seq), size)]
def getPaletteInRgb(img):
"""
Returns list of RGB tuples found in the image palette
:type img: Image.Image
:rtype: list[tuple]
"""
assert img.mode == 'P', "image should be palette mode"
pal = img.getpalette()
colors = chunk(pal, 3, False)
return colors
# Usage
im = Image.open("image.gif")
pal = getPalletteInRgb(im)
DESCRIBE <table>;
This is acutally a shortcut for:
SHOW COLUMNS FROM <table>;
In any case, there are three possible values for the "Key" attribute:
PRI
UNI
MUL
The meaning of PRI
and UNI
are quite clear:
PRI
=> primary keyUNI
=> unique keyThe third possibility, MUL
, (which you asked about) is basically an index that is neither a primary key nor a unique key. The name comes from "multiple" because multiple occurrences of the same value are allowed. Straight from the MySQL documentation:
If
Key
isMUL
, the column is the first column of a nonunique index in which multiple occurrences of a given value are permitted within the column.
There is also a final caveat:
If more than one of the Key values applies to a given column of a table, Key displays the one with the highest priority, in the order
PRI
,UNI
,MUL
.
As a general note, the MySQL documentation is quite good. When in doubt, check it out!
Oh there are many differences you will need to consider
Views for selection:
Views for insertion/updates:
Drawbacks
If you are using Ubuntu 14.04 ffmpeg
is not available. You can install it by using the instructions directly from https://www.ffmpeg.org/download.html.
In short you will have to:
sudo add-apt-repository ppa:mc3man/trusty-media
sudo apt-get update
sudo apt-get install ffmpeg gstreamer0.10-ffmpeg
If this does not work maybe try using sudo apt-get dist-upgrade
but this may broke things in your system.
$total=0;
foreach($group as $key=>$value)
{
echo $key. " = " .$value. "<br>";
$total+= $value;
}
echo $total;
Add android:checked = "true"
in your activity.xml
Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.
I've implemented it like this:
Public Function LastRowWithData(ByVal strCol As String, ByVal intRow As Integer) As Long
Range(strCol & intRow).Select
LastRowWithData= ActiveSheet.Cells(ActiveSheet.Rows.Count, strCol).End(xlUp).Row
End Function
This is the developers page of the Open WhatsApp official page: http://openwhatsapp.org/develop/
You can find a lot of information there about Yowsup.
Or, you can just go the the library's link (which I copied from the Open WhatsApp page anyway): https://github.com/tgalal/yowsup
Enjoy!
My guess is that the buttons you created are not yet on the page by the time you bind the button. Either bind each button in the $.getJSON
function, or use a dynamic binding method like:
$('body').on('click', 'button', function() {
...
});
Note you probably don't want to do this on the 'body' tag, but instead wrap the buttons in another div or something and call on
on it.
To decode HTML take a look below code
string s = "Svendborg Værft A/S";
string a = HttpUtility.HtmlDecode(s);
Response.Write(a);
Output is like
Svendborg Værft A/S
Your query ($myQuery) is failing and therefore not producing a query resource, but instead producing FALSE.
To reveal what your dynamically generated query looks like and reveal the errors, try this:
$result2 = mysql_query($myQuery) or die($myQuery."<br/><br/>".mysql_error());
The error message will guide you to the solution, which from your comment below is related to using ORDER BY on a field that doesn't exist in the table you're SELECTing from.
You can use this to get a name of any provided member:
public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
To get name of a variable:
string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);
To get name of a parameter:
public class TestClass
{
public void TestMethod(string param1, string param2)
{
string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
}
}
You can use the nameof operator for parameters, variables and properties alike:
string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);
For a new path to be added to PATH environment variable in MacOS just create a new file under /etc/paths.d
directory and add write path to be set in the file. Restart the terminal. You can check with echo $PATH
at the prompt to confirm if the path was added to the environment variable.
For example: to add a new path /usr/local/sbin
to the PATH
variable:
cd /etc/paths.d
sudo vi newfile
Add the path to the newfile
and save it.
Restart the terminal and type echo $PATH
to confirm
Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.
Look here for permanently changing the heap size.
<select id="myDropDown">
<option>html5</option>
<option>javascript</option>
<option>jquery</option>
<option>css</option>
<option>sencha</option>
</select>
By jQuery:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
//close dropdown
myDropDown.attr('size',0);
By javascript:
var myDropDown=document.getElementById("myDropDown");
var length = myDropDown.options.length;
//open dropdown
myDropDown.size = length;
//close dropdown
myDropDown.size = 0;
Copied from: Open close select
Try this :
public String ConvertMessage(String content_sendout){
//use unicode (004E00650077) need to change to hex (N&#x;0065&#x;0077;) first ;
String resultcontent_sendout = "";
int i = 4;
int lengthwelcomemsg = content_sendout.length()/i;
for(int nadd=0;nadd<lengthwelcomemsg;nadd++){
if(nadd == 0){
resultcontent_sendout = "&#x"+content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
}else if(nadd == lengthwelcomemsg-1){
resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";";
}else{
resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
}
}
return resultcontent_sendout;
}
Here's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".
$.ajax({
url:/ControllerName/ActionName,
data: "id=" + Id + "¶m2=" + param2,
type: "GET",
success: function(data){
// code here
},
error: function(passParams){
// code here
}
});
Another alternative will be to use the data-ajax on a link.
<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>
Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.
<div id="_content"></div>
Not really a direct answer to ur question but its some info u should be aware of ;).
If all you want to do is have a checkbox that checks, don't worry about doing it with JQuery. That is default functionality of a checkbox on click. However, if you want to do additional things, you can add them with JQuery. Prior to jQuery 1.9, you can use use $(this).attr('checked');
to get the value instead of $(this).attr('checked', true);
, as the second will set the value.
Here is a fiddle demonstration that shows the default checkbox functionality vs. what you are doing with JQuery.
Note: After JQuery 1.6, you should use $(this).prop;
instead of $(this).attr
in all three places (thanks @Whatevo for pointing this out and see here for further details).
UPDATE:
Sorry, missed the requirement that it had to be a radio button. You still may want to consider the checkbox, but here is the updated code for the radio input version. It works by setting the previousValue
as an attribute on the checkbox, as I don't think prop
is supported in 1.3.2. You could also do this in a scoped variable, as some people don't like setting random attributes on fields. Here is the new example.
UPDATE 2:
As Josh pointed out, the previous solution only worked with one radio button. Here's a function that makes a group of radios deselectable by their name, and a fiddle:
var makeRadiosDeselectableByName = function(name){
$('input[name=' + name + ']').click(function() {
if($(this).attr('previousValue') == 'true'){
$(this).attr('checked', false)
} else {
$('input[name=' + name + ']').attr('previousValue', false);
}
$(this).attr('previousValue', $(this).attr('checked'));
});
};
Transparent background will help you see what behind the element, in this case what behind your td
is in fact the parent table. So we have no way to achieve what you want using pure CSS. Even using script can't solve it in a direct way. We can just have a workaround using script based on the idea of using the same background for both the body and the td
. However we have to update the background-position
accordingly whenver the window is resized. Here is the code you can use with the default background position of body
(which is left top
, otherwise you have to change the code to update the background-position
of the td
correctly):
HTML:
<table id = "MainTable">
<tr>
<td width = "20%"></td>
<td width = "80%" id='test'>
<table>
<tr><td>something interesting here</td></tr>
<tr><td>another thing also interesting out there</td></tr>
</table>
</td>
</tr>
</table>
CSS:
/* use the same background for the td #test and the body */
#test {
padding:40px;
background:url('http://placekitten.com/800/500');
}
body {
background:url('http://placekitten.com/800/500');
}
JS (better use jQuery):
//code placed in onload event handler
function updateBackgroundPos(){
var pos = $('#test').offset();
$('#test').css('background-position',
-pos.left + 'px' + " " + (-pos.top + 'px'));
};
updateBackgroundPos();
$(window).resize(updateBackgroundPos);
Try resizing the viewport, you'll see the background-position
updated correctly, which will make an effect looking like the background of the td
is transparent to the body.
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:
$(".bgHeaderH2").text();
Simple
function timeToSeconds($time)
{
$timeExploded = explode(':', $time);
if (isset($timeExploded[2])) {
return $timeExploded[0] * 3600 + $timeExploded[1] * 60 + $timeExploded[2];
}
return $timeExploded[0] * 3600 + $timeExploded[1] * 60;
}
If you know that the files are located in the same directory dir
of the website site
and have the following format: filename_01.jpg, ..., filename_10.jpg then download all of them:
import requests
for x in range(1, 10):
str1 = 'filename_%2.2d.jpg' % (x)
str2 = 'http://site/dir/filename_%2.2d.jpg' % (x)
f = open(str1, 'wb')
f.write(requests.get(str2).content)
f.close()
The following code works for me on owl carousel .
https://github.com/OwlFonk/OwlCarousel
$(".owl-carousel").owlCarousel({
items: 1,
autoplay: true,
navigation: true,
navigationText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});
For OwlCarousel2
https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html
$(".owl-carousel").owlCarousel({
items: 1,
autoplay: true,
nav: true,
navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});
There are a few ways. One of the simplest is to create a my-paths.pth
file (as described here). This is just a file with the extension .pth
that you put into your system site-packages
directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/
and it will add that directory to the path.
You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path
. See the documentation.
Note that no matter what you do, sys.path
contains directories not files. You can't "add a file to sys.path
". You always add its directory and then you can import the file.
If all you are trying to do is find the IP address that corresponds to a domain name, like google.com
, this is very easy on every machine connected to the Internet.
Simply run the ping
command from any command prompt. Typing something like
ping google.com
will give you (among other things) that information.
Most of the answers here are either 'UnSafe" or not LittleEndian safe. BitConverter is not LittleEndian safe. So building on an example in here (see the post by PZahra) I made a LittleEndian safe version simply by reading the byte array in reverse when BitConverter.IsLittleEndian == true
void Main(){
Console.WriteLine(BitConverter.IsLittleEndian);
byte[] bytes = BitConverter.GetBytes(0xdcbaabcdfffe1608);
//Console.WriteLine(bytes);
string hexStr = ByteArrayToHex(bytes);
Console.WriteLine(hexStr);
}
public static string ByteArrayToHex(byte[] data)
{
char[] c = new char[data.Length * 2];
byte b;
if(BitConverter.IsLittleEndian)
{
//read the byte array in reverse
for (int y = data.Length -1, x = 0; y >= 0; --y, ++x)
{
b = ((byte)(data[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(data[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
}
else
{
for (int y = 0, x = 0; y < data.Length; ++y, ++x)
{
b = ((byte)(data[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(data[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
}
return String.Concat("0x",new string(c));
}
It returns this:
True
0xDCBAABCDFFFE1608
which is the exact hex that went into the byte array.
The easiest way (offering something near what you wrote) is to use Boost.Regex, specifically regex_replace.
std::string has built in find() and replace() methods, but they are more cumbersome to work with as they require dealing with indices and string lengths.
I think you could do it using a specs file.
Under MinGW you could run
gcc -dumpspecs > specs
Where it says
*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT}
You change it to
*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT} -std=c++11
And then place it in
/mingw/lib/gcc/mingw32/<version>/specs
I'm sure you could do the same without a MinGW build. Not sure where to place the specs file though.
The folder is probably either /gcc/lib/ or /gcc/.
use get(0).tagName. See this link
I realise this is an old question, but another possible consideration depending on your exact requirements is that validating on https://validator.w3.org/ generates warnings as follows:
Warning: The form role is unnecessary for element form.
Unfortunately, IE and VLC don't really work right now... I found this on the vlc forums:
VLC included activex support up until version 0.8.6, I believe. At that time, you could
access a cab on the videolan and therefore 'automatic' installation into IE and Firefox
family browsers was fine. Thereafter support for activex seemed to stop; no cab, no
activex component.
VLC 1.0.* once again contains activex support, and that's brilliant. A good decision in
my opinion. What's lacking is a cab installer for the latest version.
This basically means that even if you found a way to make it work, anyone trying to view the video on your site in IE would have to download and install the entire VLC player program to have it work in IE, and users probably don't want to do that. I can't get your code to work in firefox or IE8 on my boyfriends computer, although I might not have been putting the video address in properly... I get some message about no video output...
I'll take a guess and say it probably works for you locally because you have VLC installed, but your server doesn't. Unfortunately you'll probably have to use Windows media player or something similar (Microsoft is great at forcing people to use their stuff!)
And if you're wondering, it appears that the reason there is no cab file is because of the cost of having an active-x control signed.
It's rather simple to have your page use VLC for firefox and chrome users, and Windows Media Player for IE users, if that would work for you.
I think the problem is the realpath of the file. For example your script is working on './', your file is inside the directory './xml'. So better check if the file exists or not, before you get filemtime or unlink it:
function deleteOldFiles(){
if ($handle = opendir('./xml')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/^.*\.(xml|xsl)$/i", $file)){
$fpath = 'xml/'.$file;
if (file_exists($fpath)) {
$filelastmodified = filemtime($fpath);
if ( (time() - $filelastmodified ) > 24*3600){
unlink($fpath);
}
}
}
}
closedir($handle);
}
}
in the received page you can use:
parse_str($str, $array); var_dump($array);
Google has moved NDK releases to GitHub. Now, the Wiki page contains links to the current stable release, to available betas, and to selected older releases.
i have seen your running code .There is one line correction in your code.
Write:
$("#wrapper").rotate(angle);
instead of:
$("#image").rotate(angle);
and you will get your desired output,hope this is what you want.
You can also have different urls for apps in one server configuration:
In /etc/nginx/sites-enabled/yourdomain:
server {
listen 80;
listen [::]:80;
server_name yourdomain.com;
location ^~ /app1/{
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:3000/;
}
location ^~ /app2/{
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:4000/;
}
}
Restart nginx:
sudo service nginx restart
Starting applications.
node app1.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from app1!\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
node app2.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from app2!\n');
}).listen(4000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:4000/');
I could not use some of the suggestions provided.
In my case I had Google Chrome being used to display an Oracle APEX Application. There were some very specific input fields that allowed you to start typing a value and a list of values would begin to be displayed and reduced as you became more specific in your typing. Once you selected the item from the list of available options, the focus would still be on the input field.
I found that my solution was easily accomplished with a custom event that throws a custom error like the following:
throw "throwing a custom error exits input and hides keyboard";
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
I was facing the same problem when I was trying to connect Mysql to a Remote Server. I had found out that I had to change the bind-address to the current private IP address of the DB server.
But when I was trying to add the bind-address =0.0.0.0
line in my.cnf
file, it was not understanding the line when I tried to create a DB.
Upon searching, I found out the original place where bind-address was declared.
The actual declaration is in : /etc/mysql/mariadb.conf.d/50-server.cnf
Therefore I changed the bind-address directly there and then all seems working.
You Can do by Two ways,
1. Cloning the Remote Repo to your Local host
example: git clone https://github.com/user-name/repository.git
2. Pulling the Remote Repo to your Local host
First you have to create a git local repo by,
example: git init or git init repo-name then, git pull https://github.com/user-name/repository.git
That's all, All commits and branch in the remote repo now available in the local repository of your computer.
Happy Coding, cheers -:)
use jackson to convert json input stream to the map or object http://jackson.codehaus.org/
there are also some other usefull libraries for json, you can google: json java
Had the same problem with spaces. Combination of URL and URI solved it:
URL url = new URL("file:/E:/Program Files/IBM/SDP/runtimes/base");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
On more than 3 occasions working with SQL Server 2014, I have had a database convert to Single User mode without me changing anything. It must have occurred during database creation somehow. All of the methods above never worked as I always received an error that the database was in single user mode and could not be connected to.
The only thing I got to work was restarting the SQL Server Windows Service. That allowed me to connect to the database and make the necessary changes or to delete the database and start over.
A cleaner way to gain higher control might be to package the retry stuff into a function and make that function retriable using a decorator and whitelist the exceptions.
I have created the same here: http://www.praddy.in/retry-decorator-whitelisted-exceptions/
Reproducing the code in that link :
def retry(exceptions, delay=0, times=2):
"""
A decorator for retrying a function call with a specified delay in case of a set of exceptions
Parameter List
-------------
:param exceptions: A tuple of all exceptions that need to be caught for retry
e.g. retry(exception_list = (Timeout, Readtimeout))
:param delay: Amount of delay (seconds) needed between successive retries.
:param times: no of times the function should be retried
"""
def outer_wrapper(function):
@functools.wraps(function)
def inner_wrapper(*args, **kwargs):
final_excep = None
for counter in xrange(times):
if counter > 0:
time.sleep(delay)
final_excep = None
try:
value = function(*args, **kwargs)
return value
except (exceptions) as e:
final_excep = e
pass #or log it
if final_excep is not None:
raise final_excep
return inner_wrapper
return outer_wrapper
@retry(exceptions=(TimeoutError, ConnectTimeoutError), delay=0, times=3)
def call_api():
You can't have duplicate keys in a Map
. You can rather create a Map<Key, List<Value>>
, or if you can, use Guava's Multimap
.
Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");
System.out.println(multimap.get(1)); // Prints - [rohit, jain]
And then you can get the java.util.Map
using the Multimap#asMap()
method.
Here's the simple check, and creates the dir if doesn't exists:
## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)
if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
print("Dir already exists!")
}
Here is a simple example that I tried to explain.
<div>
<div *ngIf="product"> <!--If "product" exists-->
<h2>Product Details</h2><hr>
<h4>Name: {{ product.name }}</h4>
<h5>Price: {{ product.price | currency }}</h5>
<p> Description: {{ product.description }}</p>
</div>
<div *ngIf="!product"> <!--If "product" not exists-->
*Product not found
</div>
</div>
Use android.util.Log
and the static methods defined there (e.g., e()
, w()
).
Just try to set local date earlier than Feb 14. Works for me! Not a complete solution but temporary solve the problem.
You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.
public class NutritionalFacts {
private final int sodium;
private final int fat;
private final int carbo;
public int getSodium(){
return sodium;
}
public int getFat(){
return fat;
}
public int getCarbo(){
return carbo;
}
public static class Builder {
private int sodium;
private int fat;
private int carbo;
public Builder sodium(int s) {
this.sodium = s;
return this;
}
public Builder fat(int f) {
this.fat = f;
return this;
}
public Builder carbo(int c) {
this.carbo = c;
return this;
}
public NutritionalFacts build() {
return new NutritionalFacts(this);
}
}
private NutritionalFacts(Builder b) {
this.sodium = b.sodium;
this.fat = b.fat;
this.carbo = b.carbo;
}
}
And now you can set the properties as follows:
NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
fat(5).build();
You can also do something:
SELECT CAST(CAST(34512367.392 AS decimal(30,9)) AS NVARCHAR(100))
Output:
34512367.392000000
Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.
I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.
If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.
string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");
string path = Server.MapPath("~/App_Data/somedata.xml");
It was very useful for me i have used in the following way to add user in active directory:
:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "
cls
:while1
if %x% leq %lent% (
dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
echo User %Uname%%x% with DC %DcName% is created
set /a "x = x + 1"
goto :while1
)
endlocal
Blank=False # this field is required.
Null=False # this field should not be null
Blank=True # this field is optional.
Null=True # Django uses empty string (''), not NULL.
Note:
Avoid using null=True
on string-based fields such as CharField
and TextField
and FileField
/ImageField
.
Ref: Django null , Django blank
Function In function python
def Greater(a,b):
if a>b:
return a
return b
def Greater_new(a,b,c,d):
return Greater(Greater(a,b),Greater(c,d))
print("Greater Number is :-",Greater_new(212,33,11,999))
I'd recommend not to use
var binaryString = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
because it
Maximum call stack size exceeded
error on 120000 bytes buffer (Chrome 29))If you exactly need synchronous solution use something like
var
binaryString = '',
bytes = new Uint8Array(arrayBuffer),
length = bytes.length;
for (var i = 0; i < length; i++) {
binaryString += String.fromCharCode(bytes[i]);
}
it is as slow as the previous one but works correctly. It seems that at the moment of writing this there is no quite fast synchronous solution for that problem (all libraries mentioned in this topic uses the same approach for their synchronous features).
But what I really recommend is using Blob
+ FileReader
approach
function readBinaryStringFromArrayBuffer (arrayBuffer, onSuccess, onFail) {
var reader = new FileReader();
reader.onload = function (event) {
onSuccess(event.target.result);
};
reader.onerror = function (event) {
onFail(event.target.error);
};
reader.readAsBinaryString(new Blob([ arrayBuffer ],
{ type: 'application/octet-stream' }));
}
the only disadvantage (not for all) is that it is asynchronous. And it is about 8-10 times faster then previous solutions! (Some details: synchronous solution on my environment took 950-1050 ms for 2.4Mb buffer but solution with FileReader had times about 100-120 ms for the same amount of data. And I have tested both synchronous solutions on 100Kb buffer and they have taken almost the same time, so loop is not much slower the using 'apply'.)
BTW here: How to convert ArrayBuffer to and from String author compares two approaches like me and get completely opposite results (his test code is here) Why so different results? Probably because of his test string that is 1Kb long (he called it "veryLongStr"). My buffer was a really big JPEG image of size 2.4Mb.
In Preferences -> General -> Web Browser, there is the option "Use internal web browser". Select "Use external web browser" instead and check "Firefox".
The answer is now obsolete. See this answer.
maven-compiler-plugin
depends on the old version of ASM which does not support Java 10 (and Java 11) yet. However, it is possible to explicitly specify the right version of ASM:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<release>10</release>
</configuration>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>6.2</version> <!-- Use newer version of ASM -->
</dependency>
</dependencies>
</plugin>
You can find the latest at https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm&core=gav
use SimpleDateFormat
to first parse()
String
to Date
and then format()
Date
to String
Write your function this way:
onToggleLoop = (event) => {
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).
I agree with others – it is asking for name clashes, ambiguities and then the fact is it is less explicit. While I can see the use of using
, my personal preference is to limit it. I would also strongly consider what some others pointed out:
If you want to find a function name that might be a fairly common name, but you only want to find it in the std
namespace (or the reverse – you want to change all calls that are not in namespace std
, namespace X
, ...), then how do you propose to do this?
You could write a program to do it, but wouldn't it be better to spend time working on your project itself rather than writing a program to maintain your project?
Personally, I actually don't mind the std::
prefix. I like the look more than not having it. I don't know if that is because it is explicit and says to me "this isn't my code... I am using the standard library" or if it is something else, but I think it looks nicer. This might be odd given that I only recently got into C++ (used and still do C and other languages for much longer and C is my favourite language of all time, right above assembly).
There is one other thing although it is somewhat related to the above and what others point out. While this might be bad practise, I sometimes reserve std::name
for the standard library version and name for program-specific implementation. Yes, indeed this could bite you and bite you hard, but it all comes down to that I started this project from scratch, and I'm the only programmer for it. Example: I overload std::string
and call it string
. I have helpful additions. I did it in part because of my C and Unix (+ Linux) tendency towards lower-case names.
Besides that, you can have namespace aliases. Here is an example of where it is useful that might not have been referred to. I use the C++11 standard and specifically with libstdc++. Well, it doesn't have complete std::regex
support. Sure, it compiles, but it throws an exception along the lines of it being an error on the programmer's end. But it is lack of implementation.
So here's how I solved it. Install Boost's regex, and link it in. Then, I do the following so that when libstdc++ has it implemented entirely, I need only remove this block and the code remains the same:
namespace std
{
using boost::regex;
using boost::regex_error;
using boost::regex_replace;
using boost::regex_search;
using boost::regex_match;
using boost::smatch;
namespace regex_constants = boost::regex_constants;
}
I won't argue on whether that is a bad idea or not. I will however argue that it keeps it clean for my project and at the same time makes it specific: True, I have to use Boost, but I'm using it like the libstdc++ will eventually have it. Yes, starting your own project and starting with a standard (...) at the very beginning goes a very long way with helping maintenance, development and everything involved with the project!
Just to clarify something: I don't actually think it is a good idea to use a name of a class/whatever in the STL deliberately and more specifically in place of. The string is the exception (ignore the first, above, or second here, pun if you must) for me as I didn't like the idea of 'String'.
As it is, I am still very biased towards C and biased against C++. Sparing details, much of what I work on fits C more (but it was a good exercise and a good way to make myself a. learn another language and b. try not be less biased against object/classes/etc which is maybe better stated as less closed-minded, less arrogant, and more accepting.). But what is useful is what some already suggested: I do indeed use list (it is fairly generic, is it not ?), and sort (same thing) to name two that would cause a name clash if I were to do using namespace std;
, and so to that end I prefer being specific, in control and knowing that if I intend it to be the standard use then I will have to specify it. Put simply: no assuming allowed.
And as for making Boost's regex part of std
. I do that for future integration and – again, I admit fully this is bias - I don't think it is as ugly as boost::regex:: ...
. Indeed, that is another thing for me. There are many things in C++ that I still have yet to come to fully accept in looks and methods (another example: variadic templates versus var arguments [though I admit variadic templates are very very useful!]). Even those that I do accept it was difficult, and I still have issues with them.
Open the application/config/config.php file and make the changes given below,
set your base url by replacing the value of $config['base_url']
, as
$config['base_url'] = 'http://localhost/YOUR_PROJECT_DIR_NAME';
make the $config['index_page']
configuration to empty as $config['index_page'] = '';
Create new .htaccess file in project root folder and use the given settings,
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|assets|images|js|css|uploads|favicon.png|favicon.ico|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
Restart the server, open the project and you'll be good to go.
I've had success with the following code. Albeit it got me a single lock for some reason (even if I've tried different LatLng pairs), it worked for me. mLocationManager
is a LocationManager
which is hooked up to a LocationListener
:
private void getMockLocation()
{
mLocationManager.removeTestProvider(LocationManager.GPS_PROVIDER);
mLocationManager.addTestProvider
(
LocationManager.GPS_PROVIDER,
"requiresNetwork" == "",
"requiresSatellite" == "",
"requiresCell" == "",
"hasMonetaryCost" == "",
"supportsAltitude" == "",
"supportsSpeed" == "",
"supportsBearing" == "",
android.location.Criteria.POWER_LOW,
android.location.Criteria.ACCURACY_FINE
);
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
newLocation.setLatitude (/* TODO: Set Some Lat */);
newLocation.setLongitude(/* TODO: Set Some Lng */);
newLocation.setAccuracy(500);
mLocationManager.setTestProviderEnabled
(
LocationManager.GPS_PROVIDER,
true
);
mLocationManager.setTestProviderStatus
(
LocationManager.GPS_PROVIDER,
LocationProvider.AVAILABLE,
null,
System.currentTimeMillis()
);
mLocationManager.setTestProviderLocation
(
LocationManager.GPS_PROVIDER,
newLocation
);
}
Sipwiz is correct the only way to do this properly is the HTTP and DNS hybrid approach. My registrar is a re-seller for Tucows and they offer root domain forwarding as a free value added service.
If your domain is blah.com they will ask you where you would like the domain forwarded to, and you type in www.blah.com. They assign the A record to their apache server and automaticly add blah.com as a DNS vhost. The vhost responds with an HTTP 302 error redirecting them to the proper URL. It's simple to script/setup and can be handled by low end would otherwise be scrapped hardware.
Run the following command for an example: curl -v eclecticengineers.com
I had the same question, and I tested 3 main solution :
(df != null) && (df.count > 0)
df.head(1).isEmpty()
as @hulin003 suggestdf.rdd.isEmpty()
as @Justin Pihony suggestand of course the 3 works, however in term of perfermance, here is what I found, when executing the these methods on the same DF in my machine, in terme of execution time :
therefore I think that the best solution is df.rdd.isEmpty()
as @Justin Pihony suggest
If you wanna ascertain if cookie is set...use
if (isset($_COOKIE['cookie']))
Actually, it happen to me when I didn't store the object as reference variable. in Entity class. Like this code:
ses.get(InsurancePolicy.class, 101);
After that, I stored the object in entity's reference variable so problem solved for me. policy=(InsurancePolicy)ses.get(InsurancePolicy.class, 101);
After that, I updated the object and it worked fine.
It had this issue "randomly" and took me sometime to realize what was wrong in my scenario.
After I have updated to React-native-cli 2.0.1, there was a message output to the log which helped me to dig and find the root cause:
JS server not recognized, continuing with build...
After researching some links I found this one:
Since I´m on windows, I ran netstat and found out that my VLC player was also running on port 8081 causing the issue. So, in my case, if I started the vlc server prior to the react-native server it wouldn´t work.
This same log message wasn´t output on previous versions of the react-native-cli, making it fail silently.
TL, DR: check if there´s anything running on the same port as the package manager (8081 by default)
I usually use 0. I don't like macros, and there's no guarantee that some third party header you're using doesn't redefine NULL to be something odd.
You could use a nullptr object as proposed by Scott Meyers and others until C++ gets a nullptr keyword:
const // It is a const object...
class nullptr_t
{
public:
template<class T>
operator T*() const // convertible to any type of null non-member pointer...
{ return 0; }
template<class C, class T>
operator T C::*() const // or any type of null member pointer...
{ return 0; }
private:
void operator&() const; // Can't take address of nullptr
} nullptr = {};
Google "nullptr" for more info.
LayerDrawable progressDrawable = (LayerDrawable) mSeekBar.getProgressDrawable();
// progress bar line *progress* color
Drawable processDrawable = progressDrawable.findDrawableByLayerId(android.R.id.progress);
// progress bar line *background* color
Drawable backgroundDrawable = progressDrawable.findDrawableByLayerId(android.R.id.background);
// progress bar line *secondaryProgress* color
Drawable secondaryProgressDrawable = progressDrawable.findDrawableByLayerId(android.R.id.secondaryProgress);
processDrawable.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
// progress bar line all color
mSeekBar.getProgressDrawable().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN);
// progress circle color
mSeekBar.getThumb().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
export EDITOR=vim
worked for me
To install composer and add to your global path:
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
run these in terminal. It does say if you get an error that usr doesn't exist, you do need to manually make it. I know an answer was selected, so this is for anyone who may see this in the future, as i am sometimes, and don't want to be advised to visit yet another site. Its simple just two lines, might have to be in sudo if you have permission error
This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2)
x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence.
x2 and y2 are the same for the other line.
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library.
There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis.
As follows:
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 10]
x2, y2 = [-1, 10], [3, -1]
plt.xlim(0, 8), plt.ylim(-2, 8)
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
I had the same problem:
tr:hover { background: #000 !important; }
allone did not work, but adding
tr:hover td { background: transparent; }
to the next line of my css did the job for me!! My problem was that some of the TDs already had a background-color assigned and I did not know that I have to set that to TRANSPARENT to make the tr:hover work.
Actually, I used it with a classnames:
.trclass:hover { background: #000 !important; }
.trclass:hover td { background: transparent; }
Thanks for these answers, they made my day!! :)
You can use shorthand syntax as of Twig 1.12.0
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...
... the request.args
is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question
And how many parameters
request.args.get()
takes.
It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).
Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.
Apart from the Distinct
extension method of LINQ, you could use a HashSet<T>
object that you initialise with your collection. This is most likely more efficient than the LINQ way, since it uses hash codes (GetHashCode
) rather than an IEqualityComparer
).
In fact, if it's appropiate for your situation, I would just use a HashSet
for storing the items in the first place.
I have implemented the same approach proposed by EC84B4 answer, but I abstracted RecycleViewAdapter and make it easily resuable by means of interfaces.
So in order to use my approach you should add following base classes and interfaces to your project:
1) Interface that provides data for Adapter (collection of generic type T, and additional parameters (if needed) of generic type P)
public interface IRecycleViewListHolder<T,P>{
P getAdapterParameters();
T getItem(int position);
int getSize();
}
2) Factory for binding your items (header/item):
public interface IViewHolderBinderFactory<T,P> {
void bindView(RecyclerView.ViewHolder holder, int position,IRecycleViewListHolder<T,P> dataHolder);
}
3) Factory for viewHolders (header/items):
public interface IViewHolderFactory {
RecyclerView.ViewHolder provideInflatedViewHolder(int viewType, LayoutInflater layoutInflater,@NonNull ViewGroup parent);
}
4) Base class for Adapter with Header:
public class RecycleViewHeaderBased<T,P> extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public final static int HEADER_TYPE = 1;
public final static int ITEM_TYPE = 0;
private final IRecycleViewListHolder<T, P> dataHolder;
private final IViewHolderBinderFactory<T,P> binderFactory;
private final IViewHolderFactory viewHolderFactory;
public RecycleViewHeaderBased(IRecycleViewListHolder<T,P> dataHolder, IViewHolderBinderFactory<T,P> binderFactory, IViewHolderFactory viewHolderFactory) {
this.dataHolder = dataHolder;
this.binderFactory = binderFactory;
this.viewHolderFactory = viewHolderFactory;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
return viewHolderFactory.provideInflatedViewHolder(viewType,layoutInflater,parent);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
binderFactory.bindView(holder, position,dataHolder);
}
@Override
public int getItemViewType(int position) {
if(position == 0)
return HEADER_TYPE;
return ITEM_TYPE;
}
@Override
public int getItemCount() {
return dataHolder.getSize()+1;
}
}
Usage example:
1) IRecycleViewListHolder implementation:
public class AssetTaskListData implements IRecycleViewListHolder<Map.Entry<Integer, Integer>, GroupedRecord> {
private List<Map.Entry<Integer, Integer>> assetCountList;
private GroupedRecord record;
public AssetTaskListData(Map<Integer, Integer> assetCountListSrc, GroupedRecord record) {
this.assetCountList = new ArrayList<>();
for(Object entry: assetCountListSrc.entrySet().toArray()){
Map.Entry<Integer,Integer> entryTyped = (Map.Entry<Integer,Integer>)entry;
assetCountList.add(entryTyped);
}
this.record = record;
}
@Override
public GroupedRecord getAdapterParameters() {
return record;
}
@Override
public Map.Entry<Integer, Integer> getItem(int position) {
return assetCountList.get(position-1);
}
@Override
public int getSize() {
return assetCountList.size();
}
}
2) IViewHolderBinderFactory implementation:
public class AssetTaskListBinderFactory implements IViewHolderBinderFactory<Map.Entry<Integer, Integer>, GroupedRecord> {
@Override
public void bindView(RecyclerView.ViewHolder holder, int position, IRecycleViewListHolder<Map.Entry<Integer, Integer>, GroupedRecord> dataHolder) {
if (holder instanceof AssetItemViewHolder) {
Integer assetId = dataHolder.getItem(position).getKey();
Integer assetCount = dataHolder.getItem(position).getValue();
((AssetItemViewHolder) holder).bindItem(dataHolder.getAdapterParameters().getRecordId(), assetId, assetCount);
} else {
((AssetHeaderViewHolder) holder).bindItem(dataHolder.getAdapterParameters());
}
}
}
3) IViewHolderFactory implementation:
public class AssetTaskListViewHolderFactory implements IViewHolderFactory {
private IPropertyTypeIconMapper iconMapper;
private ITypeCaster caster;
public AssetTaskListViewHolderFactory(IPropertyTypeIconMapper iconMapper, ITypeCaster caster) {
this.iconMapper = iconMapper;
this.caster = caster;
}
@Override
public RecyclerView.ViewHolder provideInflatedViewHolder(int viewType, LayoutInflater layoutInflater, @NonNull ViewGroup parent) {
if (viewType == RecycleViewHeaderBased.HEADER_TYPE) {
AssetBasedHeaderItemBinding item = DataBindingUtil.inflate(layoutInflater, R.layout.asset_based_header_item, parent, false);
return new AssetHeaderViewHolder(item.getRoot(), item, caster);
}
AssetBasedListItemBinding item = DataBindingUtil.inflate(layoutInflater, R.layout.asset_based_list_item, parent, false);
return new AssetItemViewHolder(item.getRoot(), item, iconMapper, parent.getContext());
}
}
4) Deriving adapter
public class AssetHeaderTaskListAdapter extends RecycleViewHeaderBased<Map.Entry<Integer, Integer>, GroupedRecord> {
public AssetHeaderTaskListAdapter(IRecycleViewListHolder<Map.Entry<Integer, Integer>, GroupedRecord> dataHolder,
IViewHolderBinderFactory binderFactory,
IViewHolderFactory viewHolderFactory) {
super(dataHolder, binderFactory, viewHolderFactory);
}
}
5) Instantiate adapter class:
private void setUpAdapter() {
Map<Integer, Integer> objectTypesCountForGroupedTask = groupedTaskRepository.getObjectTypesCountForGroupedTask(this.groupedRecordId);
AssetTaskListData assetTaskListData = new AssetTaskListData(objectTypesCountForGroupedTask, getGroupedRecord());
adapter = new AssetHeaderTaskListAdapter(assetTaskListData,new AssetTaskListBinderFactory(),new AssetTaskListViewHolderFactory(iconMapper,caster));
assetTaskListRecycler.setAdapter(adapter);
}
P.S.: AssetItemViewHolder, AssetBasedListItemBinding, etc. my application own structures that should be swapped by your own, for your own purposes.
It's an old question, however might be useful for someone like me.
lodash
has _.inRange()
function https://lodash.com/docs/4.17.4#inRange
Example:
_.inRange(3, 2, 4);
// => true
Please note that this method utilizes the Lodash
utility library, and requires access to an installed version of Lodash.
I think the problem you're having is that your JSON is a list of objects when it comes in and it doesnt directly relate to your root class.
var content
would look something like this (i assume):
[
{
"id": 3636,
"is_default": true,
"name": "Unit",
"quantity": 1,
"stock": "100000.00",
"unit_cost": "0"
},
{
"id": 4592,
"is_default": false,
"name": "Bundle",
"quantity": 5,
"stock": "100000.00",
"unit_cost": "0"
}
]
Note: make use of http://jsonviewer.stack.hu/ to format your JSON.
So if you try the following it should work:
public static List<RootObject> GetItems(string user, string key, Int32 tid, Int32 pid)
{
// Customize URL according to geo location parameters
var url = string.Format(uniqueItemUrl, user, key, tid, pid);
// Syncronious Consumption
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
return JsonConvert.DeserializeObject<List<RootObject>>(content);
}
You will need to then iterate if you don't wish to return a list of RootObject
.
I went ahead and tested this in a Console app, worked fine.
You can add an undecorated JDialog like this:
import java.awt.event.*;
import javax.swing.*;
public class TestSwing {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Parent");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
final JDialog dialog = new JDialog(frame, "Child", true);
dialog.setSize(300, 200);
dialog.setLocationRelativeTo(frame);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(button);
dialog.setUndecorated(true);
dialog.setVisible(true);
}
}
Cocoa doesn’t provide anything called abstract. We can create a class abstract which gets checked only at runtime, and at compile time this is not checked.
For PHP, Padawan with Deoplete are great solutions for having a robust PHP autocompletion in Neovim. I tried a lot of things and Padawan work like a charm!
For Vim you can use Neocomplete instead of Deoplete.
I wrote an article how to make a Vim PHP IDE if somebody is interested. Of course Padawan is part of it.
Here's a CSS-only alternative. I set this up for a search field to get an effect similar to Firefox (& a hundred other apps.)
HTML
<div class="col-md-4">
<input class="form-control" type="search" />
<span class="glyphicon glyphicon-search"></span>
</div>
CSS
.form-control {
padding-right: 30px;
}
.form-control + .glyphicon {
position: absolute;
right: 0;
padding: 8px 27px;
}