It worth mentioning that the build time will be increased for VS 2015 users after:
Install-Package Microsoft.Net.Compilers
Those who are using VS 2015 and have to keep this package in their projects can fix increased build time.
Edit file packages\Microsoft.Net.Compilers.1.2.2\build\Microsoft.Net.Compilers.props
and clean it up. The file should look like:
<Project DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>
Doing so forces a project to be built as it was before adding Microsoft.Net.Compilers
package
in api 26 with build.gradle 3.0.0 and higher you can create a font directory in res and use this line in your style
<item name="android:fontFamily">@font/your_font</item>
for change build.gradle use this in your build.gradle dependecies
classpath 'com.android.tools.build:gradle:3.0.0'
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
If you're making a dictionary only to make a list of tuples, as creating dicts like you are may be a pain, you might look into using zip()
Its especialy useful if you've got one heading, and multiple rows. For instance if I assume that you want Olympics stats for countries:
headers = ['Capital', 'Food', 'Year']
countries = [
['London', 'Fish & Chips', '2012'],
['Beijing', 'Noodles', '2008'],
]
for olympics in countries:
print zip(headers, olympics)
gives
[('Capital', 'London'), ('Food', 'Fish & Chips'), ('Year', '2012')]
[('Capital', 'Beijing'), ('Food', 'Noodles'), ('Year', '2008')]
Don't know if thats the end goal, and my be off topic, but it could be something to keep in mind.
I had the same problem, the solution was set JAVA_HOME in environment variables.
A bit late answer, but I suggest you have a look at a not well known project on codeplex called ConferenceXP
ConferenceXP is an open source research platform that provides simple, flexible, and extensible conferencing and collaboration using high-bandwidth networks and the advanced multimedia capabilities of Microsoft Windows. ConferenceXP helps researchers and educators develop innovative applications and solutions that feature broadcast-quality audio and video in support of real-time distributed collaboration and distance learning environments.
Full source (it's huge!) is provided. It implements the RTP protocol.
Use this lean and short syntax:
{ this.state.show && <MyCustomComponent /> }
Code Snippet:
div{height: calc(100vh - 10vmax)}
You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.
The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.
def method_a(sample_string):
binary = ' '.join(format(ord(x), 'b') for x in sample_string)
def method_b(sample_string):
binary = ' '.join(map(bin,bytearray(sample_string,encoding='utf-8')))
if __name__ == '__main__':
from timeit import timeit
sample_string = 'Convert this ascii strong to binary.'
print(
timeit(f'method_a("{sample_string}")',setup='from __main__ import method_a'),
timeit(f'method_b("{sample_string}")',setup='from __main__ import method_b')
)
# 9.564299999998184 2.943955828988692
method_b is substantially more efficient at converting to a byte array because it makes low level function calls instead of manually transforming every character to an integer, and then converting that integer into its binary value.
You want a java decompiler, you can use the command line tool javap
to do this. Also, Java Decompiler HOW-TO describes how you can decompile a class file.
Update
As of jQuery 3.0, the new syntax is just .on:
see this answer here and the code:
$('iframe').on('load', function() {
// do stuff
});
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
You can definitely get Boolean value from a SELECT query, you just can't use a Boolean data-type.
You can represent a Boolean with 1/0.
CASE WHEN (10 > 0) THEN 1 ELSE 0 END (It can be used in SELECT QUERY)
SELECT CASE WHEN (10 > 0) THEN 1 ELSE 0 END AS MY_BOOLEAN_COLUMN
FROM DUAL
Returns, 1 (in Hibernate/Mybatis/etc 1 is true). Otherwise, you can get printable Boolean values from a SELECT.
SELECT CASE WHEN (10 > 0) THEN 'true' ELSE 'false' END AS MY_BOOLEAN_COLUMN
FROM DUAL
This returns the string 'true'
.
As an extend to @Eugene's answer another version which will work to push code from local repo to master/develop branch .
Switch to branch ‘master’:
$ git checkout master
Merge from local repo to master:
$ git merge --no-ff FEATURE/<branch_Name>
Push to master:
$ git push
in your activity_main.xml paste this code:
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="43dp"
android:text="@string/name" />
and go to res folder->values->strings.xml paste the below code with the code that already exists:
<string name="name">Escriba su mensaje y luego seleccione el canal.</string>
the above code means that you have created a textview with id:name(android:id="@+id/name") and assigned that textview to a string with an identifier name(android:text="@string/name") in strings.xml your using that identifier name to assign the text,
In our case it ended up being a Kerberos issue. I followed the steps in this article to resolve the issue: https://techcommunity.microsoft.com/t5/SQL-Server-Support/Bulk-Insert-and-Kerberos/ba-p/317304.
It came down to configuring delegation on the machine account of the SQL Server where the BULK INSERT statement is running. The machine account needs to be able to delegate via the "cifs" service to the file server where the files are located. If you are using constrained delegation make sure to specify "Use any authenication protocol".
If DFS is involved you can execute the following Powershell command to get the name of the file server:
Get-DfsnFolderTarget -Path "\\dfsnamespace\share"
The problem with the usage of
cin>>number_variable;
is that when you input 123abc value, it will pass and your variable will contain 123.
You can use regex, something like this
double inputNumber()
{
string str;
regex regex_pattern("-?[0-9]+.?[0-9]+");
do
{
cout << "Input a positive number: ";
cin >> str;
}while(!regex_match(str,regex_pattern));
return stod(str);
}
Or you can change the regex_pattern to validate anything that you would like.
[System.IO.FileInfo] $file = Get-Item -Path $FilePath
$sequenceBOM = New-Object System.Byte[] 3
$reader = $file.OpenRead()
$bytesRead = $reader.Read($sequenceBOM, 0, 3)
$reader.Dispose()
#A UTF-8+BOM string will start with the three following bytes. Hex: 0xEF0xBB0xBF, Decimal: 239 187 191
if ($bytesRead -eq 3 -and $sequenceBOM[0] -eq 239 -and $sequenceBOM[1] -eq 187 -and $sequenceBOM[2] -eq 191)
{
$utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
[System.IO.File]::WriteAllLines($FilePath, (Get-Content $FilePath), $utf8NoBomEncoding)
Write-Host "Remove UTF-8 BOM successfully"
}
Else
{
Write-Warning "Not UTF-8 BOM file"
}
Source How to remove UTF8 Byte Order Mark (BOM) from a file using PowerShell
You can use the Task Parallel Library. To be more exact, you can use Task.Wait(TimeSpan)
:
using System.Threading.Tasks;
var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
return task.Result;
else
throw new Exception("Timed out");
The following query works. It uses each group to do the select instead of SelectMany
. SelectMany
works on each element from each collection. For example, in your query you have a result of 2 collections. SelectMany
gets all the results, a total of 3, instead of each collection. The following code works on each IGrouping
in the select portion to get your aggregate operations working correctly.
var results = from line in Lines
group line by line.ProductCode into g
select new ResultLine {
ProductName = g.First().Name,
Price = g.Sum(pc => pc.Price).ToString(),
Quantity = g.Count().ToString(),
};
Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0
) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE
).
Since your integer array cannot contain a value larger than Integer.MAX_VALUE
and smaller than Integer.MIN_VALUE
your code works across all edge cases.
"WARNING: The command completed successfully but no settings of '[user id here]' have been modified."
This warning means the setting was already set like what you want it to be. So it didn't change anything for that object.
I had a similar issue with Angular and IIS throwing a 404 status code on manual refresh and tried the most voted solution but that did not work for me. Also tried a bunch of other solutions having to deal with WebDAV and changing handlers and none worked.
Luckily I found this solution and it worked (took out parts I didn't need). So if none of the above works for you or even before trying them, try this and see if that fixes your angular deployment on iis issue.
Add the snippet to your webconfig in the root directory of your site. From my understanding, it removes the 404 status code from any inheritance (applicationhost.config, machine.config), then creates a 404 status code at the site level and redirects back to the home page as a custom 404 page.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="/index.html" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
</configuration>
Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:
import numpy as np
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
label.set_y(label.get_position()[1] - (i % 2) * 0.075)
For more background and alternatives, see this post on my blog
You can try this:
SELECT u.*, p.*
FROM users AS u LEFT JOIN (
SELECT *, ROW_NUMBER() OVER(PARTITION BY userid ORDER BY [Date] DESC) AS RowNo
FROM payments
) AS p ON u.userid = p.userid AND p.RowNo=1
Uninstall the plugins first. And then try this. This uninstaller worked like a charm (I didn't even uninstall 2015 myself, it did everything on its own)!
The most common approach is to either lowercase or uppercase the search string and the data. But there are two problems with that.
There are at least three less frequently used solutions that might be more effective.
CREATE INDEX ON groups (name::citext);
. (But see below.)CREATE
INDEX ON groups (LOWER(name));
. Having done that, you can take advantage
of the index with queries like SELECT id FROM groups WHERE LOWER(name) = LOWER('ADMINISTRATOR');
, or SELECT id FROM groups WHERE LOWER(name) = 'administrator';
You have to remember to use LOWER(), though.The citext module doesn't provide a true case-insensitive data type. Instead, it behaves as if each string were lowercased. That is, it behaves as if you had called lower()
on each string, as in number 3 above. The advantage is that programmers don't have to remember to lowercase strings. But you need to read the sections "String Comparison Behavior" and "Limitations" in the docs before you decide to use citext.
For anyone still strugging (like me...) after the above more expert replies, this works in Visual Studio 2019:
outputString = Regex.Replace(inputString, @"\W", "_");
Remember to add
using System.Text.RegularExpressions;
type-specific formatting
can be used as well:
t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)
Output:
'02/23/2012'
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
Here's some code with a dummy geom_blank
layer,
range_act <- range(range(results$act), range(results$pred))
d <- reshape2::melt(results, id.vars = "pred")
dummy <- data.frame(pred = range_act, value = range_act,
variable = "act", stringsAsFactors=FALSE)
ggplot(d, aes(x = pred, y = value)) +
facet_wrap(~variable, scales = "free") +
geom_point(size = 2.5) +
geom_blank(data=dummy) +
theme_bw()
Converted the input file to include \N
for the blank column data using the below sed command in UNix terminal:
sed -i 's/,,/,\\N,/g' $file_name
and then use LOAD DATA INFILE
command to load to mysql
Try the command spyder3
If you check the scripts folder you'll find spyder3.exe
I have seen this error occur when the plugins that are needed are not specifically mentioned in the pom. So
mvn clean install
will give the exception if this is not added:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
Likewise,
mvn clean install deploy
will fail on the same exception if something like this is not added:
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
It makes sense, but a clearer error message would be welcome
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
As of C# 7 you could also use this:
if (clientsParsed["objects"] is JArray clients)
{
foreach (JObject item in clients.Children())
{
if (item["thisParameter"] as JToken itemToken)
{
command.Parameters["@MyParameter"].Value = JTokenToSql(itemToken);
}
}
}
The is Operator checks the Type and if its corrects the Value is inside the clients variable.
use this in code :
from selenium import webdriver
driver = webdriver.Firefox() # or Chrome()
driver.implicitly_wait(10) # seconds
driver.get("http://www.......")
or you can use this code if you are looking for a specific tag :
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox() #or Chrome()
driver.get("http://www.......")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "tag_id"))
)
finally:
driver.quit()
My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.
Inside [app.config] :
First, under 'configSections', you need to add below piece of code;
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)
<log4net debug="true">
<logger name="log">
<level value="All"></level>
<appender-ref ref="RollingLogFileAppender" />
</logger>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="1" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
</layout>
</appender>
</log4net>
Inside Calling Class :
Inside the class where you are going to use this log4net, you need to declare below piece of code.
ILog log = LogManager.GetLogger("log");
Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.
log.Error("message");
For the same issue on Windows7
You will see an error like this if your environment variables/ system variables are incorrectly set:
Fatal Python error: Py_Initialize: unable to load the file system codec
ImportError: No module named 'encodings'
Current thread 0x00001db4 (most recent call first):
Fixing this is really simple:
When you download Python3.x version, and run the .exe file, it gives you an option to customize where in your system you want to install Python. For example, I chose this location: C:\Program Files\Python36
Then open system properties and go to "Advanced" tab (Or you can simply do this: Go to Start > Search for "environment variables" > Click on "Edit the system environment variables".) Under the "Advanced" tab, look for "Environment Variables" and click it. Another window with name "Environment Variables" will pop up.
Now make sure your user variables have the correct Python path listed in "Path Variable". In my example here, you should see C:\Program Files\Python36. If you do not find it there, add it, by selecting Path Variable field and clicking Edit.
Last step is to double-check PYTHONHOME and PYTHONPATH fields under System Variables in the same window. You should see the same path as described above. If not add it there too.
Then click OK and go back to CMD terminal, and try checking for python. The issue should now be resolved. It worked for me.
All the above answers are great, but I'd like to chime in here. If you did not spot any issue mentioned above, try clear up your working environment. It worked for me.
You need to use v-bind:
or its alias :
. For example,
<a v-bind:href="'/job/'+ r.id">
or
<a :href="'/job/' + r.id">
In newer versions change was made to the flags: from the documentation:
--extended-insert, -e
Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.
--opt
This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.
Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.
--skip-extended-insert
Turn off extended-insert
You can use bytes(list).decode()
to do this - and list(string.encode())
to get the values back.
Where are you allocating memory for your buffer
? The line where you invoke bzero
invokes undefined behavior since buffer does not point to any valid region of memory.
char *buffer = new char[ BUFFER_SIZE ];
// do processing
// don't forget to release
delete[] buffer;
Usually, instance methods are global methods. That means they are available in all instances of the class on which they were defined. In contrast, a singleton method is implemented on a single object.
Ruby stores methods in classes and all methods must be associated with a class. The object on which a singleton method is defined is not a class (it is an instance of a class). If only classes can store methods, how can an object store a singleton method? When a singleton method is created, Ruby automatically creates an anonymous class to store that method. These anonymous classes are called metaclasses, also known as singleton classes or eigenclasses. The singleton method is associated with the metaclass which, in turn, is associated with the object on which the singleton method was defined.
If multiple singleton methods are defined within a single object, they are all stored in the same metaclass.
class Zen
end
z1 = Zen.new
z2 = Zen.new
class << z1
def say_hello
puts "Hello!"
end
end
z1.say_hello # Output: Hello!
z2.say_hello # Output: NoMethodError: undefined method `say_hello'…
In the above example, class << z1 changes the current self to point to the metaclass of the z1 object; then, it defines the say_hello method within the metaclass.
Classes are also objects (instances of the built-in class called Class). Class methods are nothing more than singleton methods associated with a class object.
class Zabuton
class << self
def stuff
puts "Stuffing zabuton…"
end
end
end
All objects may have metaclasses. That means classes can also have metaclasses. In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self. Hence, the stuff method is defined within the metaclass of the Zabuton class. The above example is just another way to define a class method. IMHO, it's better to use the def self.my_new_clas_method syntax to define class methods, as it makes the code easier to understand. The above example was included so we understand what's happening when we come across the class << self syntax.
Additional info can be found at this post about Ruby Classes.
My installer copied a log.txt file which had been generated on an XP computer. I was looking at that log file thinking it was generated on Vista. Once I fixed my log4net configuration to be "Vista Compatible". Environment.GetFolderPath was returning the expected results. Therefore, I'm closing this post.
The following SpecialFolder path reference might be useful:
Output On Windows Server 2003:
SpecialFolder.ApplicationData: C:\Documents and Settings\blake\Application Data SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Documents and Settings\blake\Desktop SpecialFolder.LocalApplicationData: C:\Documents and Settings\blake\Local Settings\Application Data SpecialFolder.MyDocuments: C:\Documents and Settings\blake\My Documents SpecialFolder.System: C:\WINDOWS\system32`
Output on Vista:
SpecialFolder.ApplicationData: C:\Users\blake\AppData\Roaming SpecialFolder.CommonApplicationData: C:\ProgramData SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Users\blake\Desktop SpecialFolder.LocalApplicationData: C:\Users\blake\AppData\Local SpecialFolder.MyDocuments: C:\Users\blake\Documents SpecialFolder.System: C:\Windows\system32
In Windows, it could be a wrong path in "System environment variables". "Path" to the php.exe directory must be the good one.
Adapted from http://docs.python.org/library/sqlite3.html:
# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]:
c.execute('insert into stocks values (?,?,?,?,?)', t)
You can use generator expressions like this:
gen = (x for x in xyz if x not in a)
for x in gen:
print x
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
For one, you don't seem to be including jQuery itself in the header but only a bunch of plugins. As for the '<' error, it's impossible to tell without seeing the generated HTML.
Use the values
attribute to return the values as a np array and then use [0]
to get the first value:
In [4]:
df.loc[df.Letters=='C','Letters'].values[0]
Out[4]:
'C'
EDIT
I personally prefer to access the columns using subscript operators:
df.loc[df['Letters'] == 'C', 'Letters'].values[0]
This avoids issues where the column names can have spaces or dashes -
which mean that accessing using .
.
you need external library
json-lib-2.2.2-jdk15.jar
List mybeanList = new ArrayList();
mybeanList.add("S");
mybeanList.add("b");
JSONArray jsonA = JSONArray.fromObject(mybeanList);
System.out.println(jsonA);
Google Gson is the best library http://code.google.com/p/google-gson/
Table Name
sp_rename 'db_name.old_table_name', 'new_table_name'
Column
sp_rename 'db_name.old_table_name.name' 'userName', 'COLUMN'
Index
sp_rename 'db_name.old_table_name.id', 'product_ID', 'INDEX'
also available for statics and datatypes
its very simple
just write:
//first create table named test....
create table test (name varchar2(10),age number(5));
//when you run the above code a table will be created....
//now we have to insert a name & an age..
Make sure age will be inserted via opening a form that seeks our help to enter the value in it
insert into test values('Deepak', :age);
//now run the above code and you'll get "1 row inserted" output...
/now run the select query to see the output
select * from test;
//that's all ..Now i think no one has any queries left over accepting a user data...
Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup)
.
So, for example, I have:
private string DoSomethingToMyString(string input)
{
// blah
}
Instead of explicitly stating the variable to be used like this:
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}
I can just omit the name of the var:
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}
If that number represents milliseconds, use the Date's constructor :
var myDate = new Date(1238540400000);
Just to add something I was missing from all the answers - even if it seems to be silly and obvious as soon as you know:
The file has to be named "App.config" or "app.config" and can be located in your project at the same level as e.g. Program.cs.
I do not know if other locations are possible, other names (like application.conf, as suggested in the ODP.net documentation) did not work for me.
PS. I started with Visual Studio Code and created a new project with "dotnet new". No configuration file is created in this case, I am sure there are other cases. PPS. You may need to add a nuget package to be able to read the config file, in case of .NET CORE it would be "dotnet add package System.Configuration.ConfigurationManager --version 4.5.0"
If you deployed the package to the "Integration Services Catalog" on SSMS you can retrieve the package using Visual studio.
I know this is question is really old, but I found an easy and simple jQuery solution in css-tricks. That's the one I'm using now.
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
These are the rules of the C++ language:
12
) is a "rvalue"int &ri = 12;
is ill-formedYou have to understand that these are C++ rules. They just are.
It is easy to invent a different language, say C++', with slightly different rules. In C++', it would be permitted to create a non-const reference with a rvalue. There is nothing inconsistent or impossible here.
But it would allow some risky code where the programmer might not get what he intended, and C++ designers rightly decided to avoid that risk.
well distinct can be slower than group by on some occasions in postgres (dont know about other dbs).
tested example:
postgres=# select count(*) from (select distinct i from g) a;
count
10001
(1 row)
Time: 1563,109 ms
postgres=# select count(*) from (select i from g group by i) a;
count
10001
(1 row)
Time: 594,481 ms
http://www.pgsql.cz/index.php/PostgreSQL_SQL_Tricks_I
so be careful ... :)
Just remove white space of all folders present in the given path for example Program Files You can remove it by following steps-> Open elevated cmd, In the command prompt execute: mklink /J C:\Program-Files "C:\Program Files" This will remove space and replace it with "-". Better do this with both sdk and jdk path. This works :)
Java has a special static method:
public static void main(String[] args) { ... }
which is executed in a class when the class is started with a java command line:
$ java Class
would execute said method in the class "Class" if it existed.
public void run() { ... }
is required by the Runnable interface, or inherited from the Thread class when creating new threads.
No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps
1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option.
3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.
Above process was to make build manually. If You want android studio to automatically Signing Your App
In Android Studio, you can configure your project to sign your release APK automatically during the build process:
On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. Figure 4. Create a signing configuration in Android Studio.
Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. Figure 5. Select a signing configuration in Android Studio.
4:Most Important thing that make debuggable=false at gradle.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard- android.txt'), 'proguard-rules.txt'
debuggable false
jniDebuggable false
renderscriptDebuggable false
zipAlignEnabled true
}
}
visit for more in info developer.android.com
its very true on oracle as well as sql is "users" is a reserved words just change it , it will serve u the best if u like change it to this
UPDATE system_info set field_value = 'NewValue'
FROM system_users users JOIN system_info info ON users.role_type = info.field_desc
where users.user_name = 'uname'
The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:
>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'
You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!
@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request.
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
@ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public @ResponseBody String helloWorld() {
return "Hello World";
}
Alternatively, we can use @RestController annotation in place of @Controller
annotation. This will remove the need to using @ResponseBody
.
What about using the Double(String) constructor? So,
protein = new Double(p);
Don't know why it would be different, but might be worth a shot.
Move the -h and specify that mydir is a directory
attrib /S /D /L -H mydir\*.*
Exception : java.net.ConnectException
This means your request didn't getting response from server in stipulated time. And their are some reasons for this exception:
I' ve got the same problem. My solution is this :
If you using LinQ2SQL in your project, Open your dbml file in Visual Studio and change Serialization Mode to "Unidirectional" on
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("fromaddress", "password")
msg = "HI!"
server.sendmail("fromaddress", "receiveraddress", msg)
server.quit()
'Watching' STL containers while debugging is somewhat of a problem. Here are 3 different solutions I have used in the past, none of them is perfect.
1) Use GDB scripts from http://clith.com/gdb_stl_utils/ These scripts allow you to print the contents of almost all STL containers. The problem is that this does not work for nested containers like a stack of sets.
2) Visual Studio 2005 has fantastic support for watching STL containers. This works for nested containers but this is for their implementation for STL only and does not work if you are putting a STL container in a Boost container.
3) Write your own 'print' function (or method) for the specific item you want to print while debugging and use 'call' while in GDB to print the item. Note that if your print function is not being called anywhere in the code g++ will do dead code elimination and the 'print' function will not be found by GDB (you will get a message saying that the function is inlined). So compile with -fkeep-inline-functions
I posted this question and never saw the feedback (which came in several months after, it seems :).
As Kinlan mentioned, ALLOW-FROM is not supported in all browsers as an X-Frame-Options value.
The solution was to branch based on browser type. For IE, ship X-Frame-Options. For everyone else, ship X-Content-Security-Policy.
Hope this helps, and sorry for taking so long to close the loop!
One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.
This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.
In Spring 4.0.9, we were able to send this
JSONObject jsonCredential = new JSONObject();
jsonCredential.put(APPLICATION_CREDENTIALS, data);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);
In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.
The way Convertors work is that if you have it in your classpath, they get registered.
Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.
Once we added I could see the converter being registered.
Add an extra apostrophe '
to the MessageFormat
pattern String
to ensure the '
character is displayed
String text =
java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
^
An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc
A single quote itself must be represented by doubled single quotes '' throughout a String.
The String
You\\'re
is equivalent to adding a backslash character to the String
so the only difference will be that You\re
will be produced rather than Youre
. (before double quote solution ''
applied)
Why don't you simply use set_index
method?
In : col = ['a','b','c']
In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
In : data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In : data2 = data.set_index('a')
In : data2
Out:
b c
a
1 2 3
10 11 12
20 21 22
Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.
Seems to work
$(".selector").change(function() {
var $value = $(this).val();
var $title = $(this).children('option[value='+$value+']').html();
$('#bacon').val($title);
});
Just check with your firebug. And don't put css on hidden input.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s
instead:
.replace(/\s/g,'')
You can also use .replaceAll
if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll
, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
You can just share the pixeldata between a both namespaces ( Media and Drawing) by writing a custom bitmapsource. The conversion will happen immediately and no additional memory will be allocated. If you do not want to explicitly create a copy of your Bitmap this is the method you want.
class SharedBitmapSource : BitmapSource, IDisposable
{
#region Public Properties
/// <summary>
/// I made it public so u can reuse it and get the best our of both namespaces
/// </summary>
public Bitmap Bitmap { get; private set; }
public override double DpiX { get { return Bitmap.HorizontalResolution; } }
public override double DpiY { get { return Bitmap.VerticalResolution; } }
public override int PixelHeight { get { return Bitmap.Height; } }
public override int PixelWidth { get { return Bitmap.Width; } }
public override System.Windows.Media.PixelFormat Format { get { return ConvertPixelFormat(Bitmap.PixelFormat); } }
public override BitmapPalette Palette { get { return null; } }
#endregion
#region Constructor/Destructor
public SharedBitmapSource(int width, int height,System.Drawing.Imaging.PixelFormat sourceFormat)
:this(new Bitmap(width,height, sourceFormat) ) { }
public SharedBitmapSource(Bitmap bitmap)
{
Bitmap = bitmap;
}
// Use C# destructor syntax for finalization code.
~SharedBitmapSource()
{
// Simply call Dispose(false).
Dispose(false);
}
#endregion
#region Overrides
public override void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)
{
BitmapData sourceData = Bitmap.LockBits(
new Rectangle(sourceRect.X, sourceRect.Y, sourceRect.Width, sourceRect.Height),
ImageLockMode.ReadOnly,
Bitmap.PixelFormat);
var length = sourceData.Stride * sourceData.Height;
if (pixels is byte[])
{
var bytes = pixels as byte[];
Marshal.Copy(sourceData.Scan0, bytes, 0, length);
}
Bitmap.UnlockBits(sourceData);
}
protected override Freezable CreateInstanceCore()
{
return (Freezable)Activator.CreateInstance(GetType());
}
#endregion
#region Public Methods
public BitmapSource Resize(int newWidth, int newHeight)
{
Image newImage = new Bitmap(newWidth, newHeight);
using (Graphics graphicsHandle = Graphics.FromImage(newImage))
{
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphicsHandle.DrawImage(Bitmap, 0, 0, newWidth, newHeight);
}
return new SharedBitmapSource(newImage as Bitmap);
}
public new BitmapSource Clone()
{
return new SharedBitmapSource(new Bitmap(Bitmap));
}
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Protected/Private Methods
private static System.Windows.Media.PixelFormat ConvertPixelFormat(System.Drawing.Imaging.PixelFormat sourceFormat)
{
switch (sourceFormat)
{
case System.Drawing.Imaging.PixelFormat.Format24bppRgb:
return PixelFormats.Bgr24;
case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
return PixelFormats.Pbgra32;
case System.Drawing.Imaging.PixelFormat.Format32bppRgb:
return PixelFormats.Bgr32;
}
return new System.Windows.Media.PixelFormat();
}
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
_disposed = true;
}
}
#endregion
}
We were able to solve this problem by adding in the Object.Assign polyfill to the files being imported and throwing the error. We would make it the highest import, that way it would be available to the other code to be called in the stack.
import "mdn-polyfills/Object.assign";
Arrays have an indexOf
method which can be used to search for strings:
js> a = ['foo', 'bar', 'baz']
foo,bar,baz
js> a.indexOf('bar')
1
js> a.indexOf('quux')
-1
Your Code
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
Replace it By
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
I posted some code in answer to a related question on StackOverflow:
Sorting a multidimensionnal array in VBA
The code samples in that thread include:
Alain's optimised Quicksort is very shiny: I just did a basic split-and-recurse, but the code sample above has a 'gating' function that cuts down on redundant comparisons of duplicated values. On the other hand, I code for Excel, and there's a bit more in the way of defensive coding - be warned, you'll need it if your array contains the pernicious 'Empty()' variant, which will break your While... Wend comparison operators and trap your code in an infinite loop.
Note that quicksort algorthms - and any recursive algorithm - can fill the stack and crash Excel. If your array has fewer than 1024 members, I'd use a rudimentary BubbleSort.
Public Sub QuickSortArray(ByRef SortArray As Variant, _ Optional lngMin As Long = -1, _ Optional lngMax As Long = -1, _ Optional lngColumn As Long = 0) On Error Resume Next
'Sort a 2-Dimensional array
' Sample Usage: sort arrData by the contents of column 3 ' ' QuickSortArray arrData, , , 3
' 'Posted by Jim Rech 10/20/98 Excel.Programming
'Modifications, Nigel Heffernan:
' ' Escape failed comparison with empty variant ' ' Defensive coding: check inputs
Dim i As Long Dim j As Long Dim varMid As Variant Dim arrRowTemp As Variant Dim lngColTemp As Long
If IsEmpty(SortArray) Then Exit Sub End If
If InStr(TypeName(SortArray), "()") < 1 Then 'IsArray() is somewhat broken: Look for brackets in the type name Exit Sub End If
If lngMin = -1 Then lngMin = LBound(SortArray, 1) End If
If lngMax = -1 Then lngMax = UBound(SortArray, 1) End If
If lngMin >= lngMax Then ' no sorting required Exit Sub End If
i = lngMin j = lngMax
varMid = Empty varMid = SortArray((lngMin + lngMax) \ 2, lngColumn)
' We send 'Empty' and invalid data items to the end of the list: If IsObject(varMid) Then ' note that we don't check isObject(SortArray(n)) - varMid might pick up a valid default member or property i = lngMax j = lngMin ElseIf IsEmpty(varMid) Then i = lngMax j = lngMin ElseIf IsNull(varMid) Then i = lngMax j = lngMin ElseIf varMid = "" Then i = lngMax j = lngMin ElseIf varType(varMid) = vbError Then i = lngMax j = lngMin ElseIf varType(varMid) > 17 Then i = lngMax j = lngMin End If
While i <= j
While SortArray(i, lngColumn) < varMid And i < lngMax i = i + 1 Wend
While varMid < SortArray(j, lngColumn) And j > lngMin j = j - 1 Wend
If i <= j Then
' Swap the rows ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2)) For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2) arrRowTemp(lngColTemp) = SortArray(i, lngColTemp) SortArray(i, lngColTemp) = SortArray(j, lngColTemp) SortArray(j, lngColTemp) = arrRowTemp(lngColTemp) Next lngColTemp Erase arrRowTemp
i = i + 1 j = j - 1
End If
Wend
If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn) If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)
End Sub
Just one more thing that hasn't been added yet
In Python 2, if you want to print a variable that has unicode and use .format()
, then do this (make the base string that is being formatted a unicode string with u''
:
>>> text = "Université de Montréal"
>>> print(u"This is unicode: {}".format(text))
>>> This is unicode: Université de Montréal
I am using this one with my codes.
Simply add this to your criteria:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
that code will be like the select distinct * from table of the native sql. Hope this one helps.
building '_mysql' extension
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
C:\Users\TimHuang\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\python27\include -Ic:\python27\PC /Tc_mysql.c /Fobuild\temp.win-amd64-2.7\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
If you see this when you try pip install mysql-python
, the easiest way is to copy
C:\Program Files\MySQL\MySQL Connector C 6.0.2
to C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2
I tried to create the symbolic link but Windows keeps throwing me
C:\WINDOWS\system32>mklink /d "C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" "C:\Program Files\MySQL\MySQL Connector C 6.0.2\include"
The system cannot find the path specified.
Use multiple text shadows:
text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff;
body {_x000D_
font-family: sans-serif;_x000D_
background: #222;_x000D_
color: darkred;_x000D_
}_x000D_
h1 {_x000D_
text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff;_x000D_
}
_x000D_
<h1>test</h1>
_x000D_
Alternatively, you could use text stroke, which only works in webkit:
-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: #fff;
body {_x000D_
font-family: sans-serif;_x000D_
background: #222;_x000D_
color: darkred;_x000D_
}_x000D_
h1 {_x000D_
-webkit-text-stroke-width: 2px;_x000D_
-webkit-text-stroke-color: #fff;_x000D_
}
_x000D_
<h1>test</h1>
_x000D_
Also read more as CSS-Tricks.
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
You can use a extension method
public static void EnumForComboBox(this ComboBox comboBox, Type enumType)
{
var memInfo = enumType.GetMembers().Where(a => a.MemberType == MemberTypes.Field).ToList();
comboBox.Items.Clear();
foreach (var member in memInfo)
{
var myAttributes = member.GetCustomAttribute(typeof(DescriptionAttribute), false);
var description = (DescriptionAttribute)myAttributes;
if (description != null)
{
if (!string.IsNullOrEmpty(description.Description))
{
comboBox.Items.Add(description.Description);
comboBox.SelectedIndex = 0;
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
}
}
How to use ... Declare enum
using System.ComponentModel;
public enum CalculationType
{
[Desciption("LoaderGroup")]
LoaderGroup,
[Description("LadingValue")]
LadingValue,
[Description("PerBill")]
PerBill
}
This method show description in Combo box items
combobox1.EnumForComboBox(typeof(CalculationType));
You can add a form onsubmit handler, something like:
<form onsubmit="return validate();">
</form>
<script>function validate() {
// check if input is bigger than 3
var value = document.getElementById('titleeee').value;
if (value.length < 3) {
return false; // keep form from submitting
}
// else form is good let it submit, of course you will
// probably want to alert the user WHAT went wrong.
return true;
}</script>
Use of Int or Int32 are the same Int is just sugar to simplify the code for the reader.
Use the Nullable variant Int? or Int32? when you work with databases on fields containing null. That will save you from a lot of runtime issues.
The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.
you can use skimage.img_as_ubyte(yourdata)
it will make you numpy array ranges from 0->255
from skimage import img_as_ubyte
img = img_as_ubyte(data)
cv2.imshow("Window", img)
Very often it happens when the foreign key and the reference key don't have the same type or same length.
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
Assuming that the database is MS SQL Server 2012 or greater, here's a solution that works. The basic statement contains the in-line try-parse:
SELECT TRY_PARSE('02/04/2016 10:52:00' AS datetime USING 'en-US') AS Result;
Here's what we implemented in the production version:
UPDATE dbo.StagingInputReview
SET ReviewedOn =
ISNULL(TRY_PARSE(RTrim(LTrim(ReviewedOnText)) AS datetime USING 'en-US'), getdate()),
ModifiedOn = (getdate()), ModifiedBy = (suser_sname())
-- Check for empty/null/'NULL' text
WHERE not ReviewedOnText is null
AND RTrim(LTrim(ReviewedOnText))<>''
AND Replace(RTrim(LTrim(ReviewedOnText)),'''','') <> 'NULL';
The ModifiedOn and ModifiedBy columns are just for internal database tracking purposes.
See also these Microsoft MSDN references:
I use rc-classnames package.
// ES6
import c from 'rc-classnames';
// CommonJS
var c = require('rc-classnames');
<button className={c('button', {
'button--disabled': isDisabled,
'button--no-radius': !hasRadius
})} />
You can add classes in any format (Array, Object, Argument). All truthy values from arrays or Arguments plus keys in objects that equal to true
get merged together.
for example:
ReactClassNames('a', 'b', 'c') // => "a b c"
ReactClassNames({ 'a': true, 'b': false, c: 'true' }) // => "a c"
ReactClassNames(undefined, null, 'a', 0, 'b') // => "a b"
It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:
#include <iostream>
using namespace std;
int main()
{
int pause;
struct Customer
{
int uid;
string name;
};
Customer customerRecords[2];
customerRecords[0] = {25, "Bob Jones"};
customerRecords[1] = {26, "Jim Smith"};
cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
cin >> pause;
return 0;
}
Whitequark responded nicely. But with the current versions of Node.js and Express.js it requires one more line. Make sure to add the 'require http' (second line). I've posted a fuller example here that shows how this call can work. Once running, type http://localhost:8080/?name=abel&fruit=apple
in your browser, and you will get a cool response based on the code.
var express = require('express');
var http = require('http');
var app = express();
app.configure(function(){
app.set('port', 8080);
});
app.get('/', function(req, res){
res.writeHead(200, {'content-type': 'text/plain'});
res.write('name: ' + req.query.name + '\n');
res.write('fruit: ' + req.query.fruit + '\n');
res.write('query: ' + req.query + '\n');
queryStuff = JSON.stringify(req.query);
res.end('That\'s all folks' + '\n' + queryStuff);
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
})
showbookimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/**
Here REQUEST_IMAGE is the unique integer value you can pass it any integer
**/
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
}
);
then u can now give the image a file name as follows and then convert it into bitmap and later on to file
private void createImageFile(Bitmap bitmap) throws IOException {
// Create an image file name
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
FileOutputStream stream = new FileOutputStream(image);
stream.write(bytes.toByteArray());
stream.close();
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
fileUri = image.getAbsolutePath();
Picasso.with(getActivity()).load(image).into(showbookimage);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode== Activity.RESULT_OK && intent != null){
// get bundle
Bundle extras = intent.getExtras();
// get
bitMap = (Bitmap) extras.get("data");
// showbookimage.setImageBitmap(bitMap);
try {
createImageFile(bitMap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
use picasso for images to display rather fast
// in the HTML code I used some razor
@Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
massedit.py (http://github.com/elmotec/massedit) does the scaffolding for you leaving just the regex to write. It's still in beta but we are looking for feedback.
python -m massedit -e "re.sub(r'^# deb', 'deb', line)" /etc/apt/sources.list
will show the differences (before/after) in diff format.
Add the -w option to write the changes to the original file:
python -m massedit -e "re.sub(r'^# deb', 'deb', line)" -w /etc/apt/sources.list
Alternatively, you can now use the api:
>>> import massedit
>>> filenames = ['/etc/apt/sources.list']
>>> massedit.edit_files(filenames, ["re.sub(r'^# deb', 'deb', line)"], dry_run=True)
Loop invariant is a mathematical formula such as (x=y+1)
. In that example, x
and y
represent two variables in a loop. Considering the changing behavior of those variables throughout the execution of the code, it is almost impossible to test all possible to x
and y
values and see if they produce any bug. Lets say x
is an integer. Integer can hold 32 bit space in the memory. If that number exceeds, buffer overflow occurs. So we need to be sure that throughout the execution of the code, it never exceeds that space. for that, we need to understand a general formula that shows the relationship between variables.
After all, we just try to understand the behavior of the program.
This will work:
<head>
<script type="text/javascript">
function Init () {
var counter = document.getElementById ("counter");
for (var i = 1; i < 1000; i++) {
var option = new Option (i, i);
counter.options.add (option);
}
counter.focus ();
}
function OnKeyPressCounter (event, counter) {
var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
if (chCode == 68 /* + */) {
if (counter.selectedIndex < counter.options.length - 1) {
counter.selectedIndex++;
}
}
if (chCode == 45 /* - */) {
if (counter.selectedIndex > 0) {
counter.selectedIndex--;
}
}
}
</script>
</head>
<body onload="Init ()">
Use the + and - keys to increase/decrease the counter.
<select id="counter" onkeypress="OnKeyPressCounter(event, this)" style="width:80px"></select>
</body>
To get the cheapest product in each category, you use the MIN() function in a correlated subquery as follows:
SELECT categoryid,
productid,
productName,
unitprice
FROM products a WHERE unitprice = (
SELECT MIN(unitprice)
FROM products b
WHERE b.categoryid = a.categoryid)
The outer query scans all rows in the products table and returns the products that have unit prices match with the lowest price in each category returned by the correlated subquery.
To match only positive base-ten integers, that contains only ASCII digits, use:
public static boolean isNumeric(String maybeNumeric) {
return maybeNumeric != null && maybeNumeric.matches("[0-9]+");
}
You can see the println()
statements in the Run
window of Android Studio.
See detailed answer with screenshot here.
This is what worked for me
When I tried the Accepted ans my Android Studio hangs on start-up
This is the link
and This is the Command
$ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1
First, it depends on your version of R. If you've passed 2.11, you can use aggreggate with multiple results functions(summary, by instance, or your own function). If not, you can use the answer made by Justin.
Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
// Your Extended Properties
public long? OrganizationId { get; set; }
}
Then what you need is to create an extension method like so (I create mine in an new Extensions folder):
namespace App.Extensions
{
public static class IdentityExtensions
{
public static string GetOrganizationId(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
}
When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here => this.OrganizationId is a value stored in database against the user
userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));
return userIdentity;
}
Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:
in my case: using App.Extensions;
within a Controller and @using. App.Extensions
withing a .cshtml View file.
EDIT:
What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there.
Now look for the <namespaces>
tag and add your extension namespace there like so:
<add namespace="App.Extensions" />
Save your file and you're done. Now every View will know of your extensions.
You can access the Extension Method:
var orgId = User.Identity.GetOrganizationId();
I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:
Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);
SyntaxError: non-default argument follows default argument
If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come after.
In Python 3 however, you may do the following:
def fun1(a="who is you", b="True", *, x, y):
pass
which makes x
and y
keyword only so you can do this:
fun1(x=2, y=2)
This works because there is no longer any ambiguity. Note you still can't do fun1(2, 2)
(that would set the default arguments).
Here is one solution
# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA
lm_eqn <- function(df){
m <- lm(y ~ x, df);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)
EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups
Usually this problem arises when the Child elements of a Parent Div are floated. Here is the Latest Solution of the problem:
In your CSS file write the following class called .clearfix along with the pseudo selector :after
.clearfix:after {
content: "";
display: table;
clear: both;
}
Then, in your HTML, add the .clearfix class to your parent Div. For example:
<div class="clearfix">
<div></div>
<div></div>
</div>
It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "". Also, overflow: auto; might solve the problem but it causes other problems like showing the scroll-bar and is not recommended.
Source: Blog of Lisa Catalano and Chris Coyier
I wasn't able to make the accepted answer work in a Docker container.
What worked for me was to set the Personal Access Token from github in a file .nextrc
ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n login $GITHUB_READ_TOKEN" > ~/.netrc
RUN npm install --only=production --force \
&& npm cache clean --force
RUN rm ~/.netrc
in package.json
"my-lib": "github:username/repo",
return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);
The Apache module PHP version might for some odd reason not be picking up the php.ini file as the CLI version I'd suggest having a good look at:
.ini
files that differ between php -i
and phpinfo()
via a web page*mysql.so
and the .ini
files but I think that Apache parses these as the root
userTo be really clear here, don't go searching for php.ini
files on the file system, have a look at what PHP says that it's looking at
You can do that with list-style-position: inside;
on the ul
element :
ul {
list-style-position: inside;
}
You cannot (except the type of a particular iterator implements some specific methods that make it possible).
Generally, you may count iterator items only by consuming the iterator. One of probably the most efficient ways:
import itertools
from collections import deque
def count_iter_items(iterable):
"""
Consume an iterable not reading it into memory; return the number of items.
"""
counter = itertools.count()
deque(itertools.izip(iterable, counter), maxlen=0) # (consume at C speed)
return next(counter)
(For Python 3.x replace itertools.izip
with zip
).
No need to hack your editor, or switch editors.
Instead we can come up with a script to watch your development directories and chmod files as they're created. This is what I've done in the attached bash script. You probably want to read through the comments and edit the 'config' section as fits your needs, then I would suggest putting it in your $HOME/bin/ directory and adding its execution to your $HOME/.login or similar file. Or you can just run it from the terminal.
This script does require inotifywait, which comes in the inotify-tools package on Ubuntu,
sudo apt-get install inotify-tools
Suggestions/edits/improvements are welcome.
#!/usr/bin/env bash
# --- usage --- #
# Depends: 'inotifywait' available in inotify-tools on Ubuntu
#
# Edit the 'config' section below to reflect your working directory, WORK_DIR,
# and your watched directories, WATCH_DIR. Each directory in WATCH_DIR will
# be logged by inotify and this script will 'chmod +x' any new files created
# therein. If SUBDIRS is 'TRUE' this script will watch WATCH_DIRS recursively.
# I recommend adding this script to your $HOME/.login or similar to have it
# run whenever you log into a shell, eg 'echo "watchdirs.sh &" >> ~/.login'.
# This script will only allow one instance of itself to run at a time.
# --- config --- #
WORK_DIR="$HOME/path/to/devel" # top working directory (for cleanliness?)
WATCH_DIRS=" \
$WORK_DIR/dirA \
$WORK_DIR/dirC \
" # list of directories to watch
SUBDIRS="TRUE" # watch subdirectories too
NOTIFY_ARGS="-e create -q" # watch for create events, non-verbose
# --- script starts here --- #
# probably don't need to edit beyond this point
# kill all previous instances of myself
SCRIPT="bash.*`basename $0`"
MATCHES=`ps ax | egrep $SCRIPT | grep -v grep | awk '{print $1}' | grep -v $$`
kill $MATCHES >& /dev/null
# set recursive notifications (for subdirectories)
if [ "$SUBDIRS" = "TRUE" ] ; then
RECURSE="-r"
else
RECURSE=""
fi
while true ; do
# grab an event
EVENT=`inotifywait $RECURSE $NOTIFY_ARGS $WATCH_DIRS`
# parse the event into DIR, TAGS, FILE
OLDIFS=$IFS ; IFS=" " ; set -- $EVENT
E_DIR=$1
E_TAGS=$2
E_FILE=$3
IFS=$OLDIFS
# skip if it's not a file event or already executable (unlikely)
if [ ! -f "$E_DIR$E_FILE" ] || [ -x "$E_DIR$E_FILE" ] ; then
continue
fi
# set file executable
chmod +x $E_DIR$E_FILE
done
The limit of the enhanced format notifications is documented here.
It explicitly states:
The payload must not exceed 256 bytes and must not be null-terminated.
ascandroli claims above that they were able to send messages with 1400 characters. My own testing with the new notification format showed that a message just 1 byte over the 256 byte limit was rejected. Given that the docs are very explicit on this point I suggest it is safer to use 256 regardless of what you may be able to achieve experimentally as there is no guarantee Apple won't change it to 256 in the future.
As for the alert text itself, if you can fit it in the 256 total payload size then it will be displayed by iOS. They truncate the message that shows up on the status bar, but if you open the notification center, the entire message is there. It even renders newline characters \n
.
For me it worked like I had images in icons
folder under src
and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
You may need an extra "/"
<a href="file:///server/directory/file.xlsx">Click me!</a>
Ah, and if you have a very long string that you want to break up, say of HTML, you can do it by putting a @
on each side of the outer "
- like this:
$mystring = @"
Bob
went
to town
to buy
a fat
pig.
"@
You get exactly this:
Bob
went
to town
to buy
a fat
pig.
And if you are using Notepad++, it will even highlight correctly as a string block.
Now, if you wanted that string to contain double quotes, too, just add them in, like this:
$myvar = "Site"
$mystring = @"
<a href="http://somewhere.com/somelocation">
Bob's $myvar
</a>
"@
You would get exactly this:
<a href="http://somewhere.com/somelocation">
Bob's Site
</a>
However, if you use double-quotes in that @-string like that, Notepad++ doesn't realize that and will switch out the syntax colouring as if it were not quoted or quoted, depending on the case.
And what's better is this: anywhere you insert a $variable, it DOES get interpreted! (If you need the dollar sign in the text, you escape it with a tick mark like this: ``$not-a-variable`.)
NOTICE! If you don't put the final "@
at the very start of the line, it will fail. It took me an hour to figure out that I could not indent that in my code!
Here is MSDN on the subject: Using Windows PowerShell “Here-Strings”
Here's a simpler method, that requires neither events or timeouts. It does require jQuery, however.
Use jQuery.holdReady()
(docs)
So, immediately after your jQuery script, delay the ready event.
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$.holdReady( true ); // don't fire ready until told (ie when FB loaded)
</script>
Then, in your Facebook init function, release it:
window.fbAsyncInit = function() {
FB.init({
appId: '11111111111111',
cookie: true,
xfbml: false,
version: 'v2.4'
});
// release the ready event to execute
$.holdReady( false );
};
Then you can use the ready event as normal:
$(document).ready( myApp.init );
You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.
Sub dedupe_abcd()
Dim icol As Long
With Sheets("Sheet1") '<-set this worksheet reference properly!
icol = Application.Match("abcd", .Rows(1), 0)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=icol, Header:=xlYes
End With
End With
End Sub
Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.
Here's C/C++ recursive function that makes use of dirname()
to traverse bottom-up the directory tree. It will stop as soon as it finds an existing ancestor.
#include <libgen.h>
#include <string.h>
int create_dir_tree_recursive(const char *path, const mode_t mode)
{
if (strcmp(path, "/") == 0) // No need of checking if we are at root.
return 0;
// Check whether this dir exists or not.
struct stat st;
if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode))
{
// Check and create parent dir tree first.
char *path2 = strdup(path);
char *parent_dir_path = dirname(path2);
if (create_dir_tree_recursive(parent_dir_path, mode) == -1)
return -1;
// Create this dir.
if (mkdir(path, mode) == -1)
return -1;
}
return 0;
}
You were close
/my/bash/script <<< 'This string will be sent to stdin.'
For multiline input, here-docs are suited:
/my/bash/script <<STDIN -o other --options
line 1
line 2
STDIN
Edit To the comments:
To achieve binary input, say
xxd -r -p <<BINARY | iconv -f UCS-4BE -t UTF-8 | /my/bash/script
0000 79c1 0000 306f 0000 3061 0000 3093 0000 3077 0000 3093 0000 304b 0000 3093 0000 3077 0000 3093 0000 306a 0000 8a71 0000 306b 0000 30ca 0000 30f3 0000 30bb
0000 30f3 0000 30b9 0000 3092 0000 7ffb 0000 8a33 0000 3059 0000 308b 0000 3053 0000 3068 0000 304c 0000 3067 0000 304d 0000 000a
BINARY
If you substitute cat
for /my/bash/script
(or indeed drop the last pipe), this prints:
????????????????????????????
Or, if you wanted something a little more geeky:
0000000: 0000 0000 bef9 0e3c 59f8 8e3c 0a71 d63c .......<Y..<.q.<
0000010: c6f2 0e3d 3eaa 323d 3a5e 563d 090e 7a3d ...=>.2=:^V=..z=
0000020: 7bdc 8e3d 2aaf a03d b67e b23d c74a c43d {..=*..=.~.=.J.=
0000030: 0513 d63d 16d7 e73d a296 f93d a8a8 053e ...=...=...=...>
0000040: 6583 0e3e 5a5b 173e 5b30 203e 3d02 293e e..>Z[.>[0 >=.)>
0000050: d4d0 313e f39b 3a3e 6f63 433e 1c27 4c3e ..1>..:>ocC>.'L>
0000060: cde6 543e 59a2 5d3e 9259 663e 4d0c 6f3e ..T>Y.]>.Yf>M.o>
0000070: 60ba 773e cf31 803e ee83 843e 78d3 883e `.w>.1.>...>x..>
0000080: 5720 8d3e 766a 913e beb1 953e 1cf6 993e W .>vj.>...>...>
0000090: 7a37 9e3e c275 a23e dfb0 a63e bce8 aa3e z7.>.u.>...>...>
00000a0: 441d af3e 624e b33e 017c b73e 0ca6 bb3e D..>bN.>.|.>...>
00000b0: 6fcc bf3e 15ef c33e e90d c83e d728 cc3e o..>...>...>.(.>
00000c0: c93f d03e ac52 d43e 6c61 d83e f36b dc3e .?.>.R.>la.>.k.>
00000d0: 2f72 e03e 0a74 e43e 7171 e83e 506a ec3e /r.>.t.>qq.>Pj.>
00000e0: 945e f03e 274e f43e f738 f83e f11e fc3e .^.>'N.>.8.>...>
00000f0: 0000 003f 09ee 013f 89d9 033f 77c2 053f ...?...?...?w..?
0000100: caa8 073f 788c 093f 776d 0b3f be4b 0d3f ...?x..?wm.?.K.?
0000110: 4427 0f3f 0000 113f e8d5 123f f3a8 143f D'.?...?...?...?
0000120: 1879 163f 4e46 183f 8d10 1a3f cad7 1b3f .y.?NF.?...?...?
0000130: fe9b 1d3f 1f5d 1f3f 241b 213f 06d6 223f ...?.].?$.!?.."?
0000140: bb8d 243f 3a42 263f 7cf3 273f 78a1 293f ..$?:B&?|.'?x.)?
0000150: 254c 2b3f 7bf3 2c3f 7297 2e3f 0138 303f %L+?{.,?r..?.80?
0000160: 22d5 313f ca6e 333f ".1?.n3?
Which is the sines of the first 90 degrees in 4byte binary floats
If one need to use the sp_executesql
with OUTPUT
variables:
EXEC sp_executesql @sql
,N'@p0 INT'
,N'@p1 INT OUTPUT'
,N'@p2 VARCHAR(12) OUTPUT'
,@p0
,@p1 OUTPUT
,@p2 OUTPUT;
The then()
method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:
getFeed().then(function(data) { vm.feed = data;});
The then()
function returns the promise with a resolved value of the previous then()
callback, allowing you the pass the value to subsequent callbacks:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1
GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).
This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.
Only three lines of relevant code.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with
curl
or other clients) then a possible cause could be that the endpoint expects aUser-Agent
header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g.System.setProperty("http.agent", "Netscape 1.0");
.
I found the best anwser, it work for me. Clear the value of bootstrap-datepicker:
$('#datepicker').datepicker('setDate', null);
Add value for boostrap-datepicker:
$('#datepicker').datepicker('setDate', datePicker);
There is no native version of Visual Studio for Mac OS X.
Almost all versions of Visual Studio have a Garbage rating on Wine's application database, so Wine isn't an option either, sadly.
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.
To create a new branch with a copy of your current state
git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server
Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.
I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :
cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or
#cat release_vars.yml >> vars.yml
mvn ....
Try this:
function createcodes() {
$('.authors-list tr').each(function () {
//processing this row
//how to process each cell(table td) where there is checkbox
$(this).find('td input:checked').each(function () {
// it is checked, your code here...
});
});
}
There's backtrace()
, and backtrace_symbols()
:
From the man page:
#include <execinfo.h>
#include <stdio.h>
...
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
...
One way to use this in a more convenient/OOP way is to save the result of backtrace_symbols()
in an exception class constructor. Thus, whenever you throw that type of exception you have the stack trace. Then, just provide a function for printing it out. For example:
class MyException : public std::exception {
char ** strs;
MyException( const std::string & message ) {
int i, frames = backtrace(callstack, 128);
strs = backtrace_symbols(callstack, frames);
}
void printStackTrace() {
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
}
};
...
try {
throw MyException("Oops!");
} catch ( MyException e ) {
e.printStackTrace();
}
Ta da!
Note: enabling optimization flags may make the resulting stack trace inaccurate. Ideally, one would use this capability with debug flags on and optimization flags off.
It works very well in Firefox.
Just change the top variable to any other name and try again
var w = 200;
var h = 200;
var left = Number((screen.width/2)-(w/2));
var tops = Number((screen.height/2)-(h/2));
window.open("templates/sales/index.php?go=new_sale", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);
val navigationView: NavigationView = findViewById(R.id.nv)
val header: View = navigationView.getHeaderView(0)
val tv: TextView = header.findViewById(R.id.profilename)
tv.text = "Your_Text"
This will fix your problem <3
To pass the value you must included the hidden value value="hiddenValue"
in the <input>
statement like so:
<input type="hidden" id="thisField" name="inputName" value="hiddenValue">
Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:
This code goes on the page where you want to hide the value.
<form action="anotherPage.jsp" method="GET">
<input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">
</form>
Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name)
method of the implicit request
object, as so:
<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>
The output of the above script will be:
The Hidden Value is hiddenValue
Before you check everything according to above answers, make sure your request code is not 0!!!
check the code of onRequestPermissionsResult() in FragmentActivity.java:
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
int index = (requestCode>>16)&0xffff;
if (index != 0) {
index--;
String who = mPendingFragmentActivityResults.get(index);
mPendingFragmentActivityResults.remove(index);
if (who == null) {
Log.w(TAG, "Activity result delivered for unknown Fragment.");
return;
}
Fragment frag = mFragments.findFragmentByWho(who);
if (frag == null) {
Log.w(TAG, "Activity result no fragment exists for who: " + who);
} else {
frag.onRequestPermissionsResult(requestCode&0xffff, permissions, grantResults);
}
}
}
First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):
import static org.mockito.Mockito.*;
For partial mocking and still keeping original functionality on the rest mockito offers "Spy".
You can use it as follows:
private World world = spy(new World());
To eliminate a method from being executed you could use something like this:
doNothing().when(someObject).someMethod(anyObject());
to give some custom behaviour to a method use "when" with an "thenReturn":
doReturn("something").when(this.world).someMethod(anyObject());
For more examples please find the excellent mockito samples in the doc.
You can see the privileges here.
Then you can edit the user
I have used this in the past:
html
January<span class="right">2014</span>
Css
.right {
margin-left:100%;
}
given you have a div element you need to scroll inside, try this piece of code
document.querySelector('div').scroll(x,y)
this works with me inside a div with a scroll, this should work with you in case you pointed the mouse over this element and then tried to scroll down or up. If it manually works, it should work too
This is valid YAML:
jobs:
- name: A
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
- name: B
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.
I think something like the following library could help you out to solve the missing bit of the puzzle, the getPlatform() function.
https://github.com/joeferraro/react-native-env
const EnvironmentManager = require('react-native-env');
// read an environment variable from React Native
EnvironmentManager.get('SOME_VARIABLE')
.then(val => {
console.log('value of SOME_VARIABLE is: ', val);
})
.catch(err => {
console.error('womp womp: ', err.message);
});
The only problem I see with this, that it's async code. There is a pull request to support getSync. Check it out too.
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
In C if you implement count line it will never fail. Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.
File might look some thing like this:
"hello 1
"Hello 2
"
Code below
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "file1.txt"
int main() {
FILE *fd = NULL;
int cnt, ch;
fd = fopen(FILE_NAME,"r");
if (fd == NULL) {
perror(FILE_NAME);
exit(-1);
}
while(EOF != (ch = fgetc(fd))) {
/*
* int fgetc(FILE *) returns unsigned char cast to int
* Because it has to return EOF or error also.
*/
if (ch == '\n')
++cnt;
}
printf("cnt line in %s is %d\n", FILE_NAME, cnt);
fclose(fd);
return 0;
}
Use This code Simple and Easy to Access:
Permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Follow this Code to access the GPS programmatically:
LocationManager locationManager ;
boolean GpsStatus ;
GPSStatus();
if(GpsStatus == true)
{
textview.setText("Your Location Services Is Enabled");
}else
{textview.setText("Your Location Services Is Disabled");}
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
public void GPSStatus(){
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
I have my menu in the site master page. I used the Page_Load() function to make the "Admin" menu item only visible to users with an Admin role.
using System;
using System.Linq;
using Telerik.Web.UI;
using System.Web.Security;
<telerik:RadMenu ID="menu" runat="server" RenderMode="Auto" >
<Items>
<telerik:RadMenuItem Text="Admin" Visible="true" />
</Items>
</telerik:RadMenu>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RadMenuItem item = this.menu.FindItemByText("Admin");
if (null != item)
{
if (Roles.IsUserInRole("Admin"))
{
item.Visible = true;
}
else
{
item.Visible = false;
}
}
}
}
With java-8, you can do it this way.
double[] arr = frameList.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference
double[] arr = frameList.stream().mapToDouble(d -> d).toArray(); //identity function, Java unboxes automatically to get the double value
What it does is :
Stream<Double>
from the listDoubleStream
toArray()
to get the array.it's a good idea to use a reset CSS. add this at the top of your CSS file
img, a {border:none, outline: none;}
hope this helps
function encodeToken(token){
//token must be a string .
token = typeof token == 'string' ? token : String(token)
}
User.findOne({name: 'elrrrrrrr'}, function(err, it) {
encodeToken(it._id)
})
In mongoose , the objectId is an object (console.log(typeof it._id)).
Just use .split(',')
:
var str = "How are you doing today?";
var n = str.split(" ");
In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.
7 modulo 3 --> 1
7 modulo -3 --> -2
-7 modulo 3 --> 2
-7 modulo -3 --> -1
Along with the above answers, do also consider this site; https://google-webfonts-helper.herokuapp.com/fonts
Advantage:
allows you to self-host those google fonts for better response times
choose your font(s)
E.g your_theme.css
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans Regular'), local('OpenSans-Regular'),
url('css_fonts/open-sans-v15-latin-regular.woff2') format('woff2'),
url('css_fonts/open-sans-v15-latin-regular.woff') format('woff');
}
body {
font-family: 'Open Sans',sans-serif;
}
Make sure you use port 22. Filezilla will default to port 21 for SFTP.
You can create a custom view and put it inside a GestureDetector for it to behave like a button. The benefit is that you can provide endless types of custom decoration (including making it round with specified radius) to the container.
I had the same need and found this answer ..
This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.
===========================
CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]
@comp_name varchar(55) = 'Big Company',
@comp_regno nchar(8) = '12345678',
@comp_email nvarchar(50) = '[email protected]',
@recID INT OUTPUT
-- The '@recID' is used to hold the Company auto generated ID number that we are about to grab
AS
Begin
SET NOCOUNT ON
DECLARE @tableVar TABLE (tempID INT)
-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '@recID'.
INSERT INTO comp(comp_name, comp_regno, comp_email)
OUTPUT inserted.comp_id INTO @tableVar
-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.
VALUES (@comp_name, @comp_regno, @comp_email)
SET @recID = (SELECT tempID FROM @tableVar)
-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '@recID'. '@recID' now has the ID number you want and you can use it how you want like i have used it below.
INSERT INTO staff(Staff_comp_id)
VALUES (@recID)
End
-- So there you go. You can actually grab what ever you want in the 'OUTPUT inserted.WhatEverFieldNameYouWant' line and create what fields you want in your tempory table and access it to use how ever you want.
I was looking for something like this for ages, with this detailed break down, I hope this helps.
Login in with System Admin User Account and execute below SQL Procedure.
begin
dbms_xdb.sethttpport('Your Port Number');
end;
Then open the Browser and access the below URL
I like Jaime's method with one exception, it worked better for me to re-store the referer every time:
def edit
session[:return_to] = request.referer
...
The reason is that if you edit multiple objects, you will always be redirected back to the first URL you stored in the session with Jaime's method. For example, let's say I have objects Apple and Orange. I edit Apple and session[:return_to]
gets set to the referer of that action. When I go to edit Oranges using the same code, session[:return_to]
will not get set because it is already defined. So when I update the Orange, I will get sent to the referer of the previous Apple#edit action.
The following can be used to retrieve JSESSIONID:
function getJSessionId(){
var jsId = document.cookie.match(/JSESSIONID=[^;]+/);
if(jsId != null) {
if (jsId instanceof Array)
jsId = jsId[0].substring(11);
else
jsId = jsId.substring(11);
}
return jsId;
}
I had a similar problem.
I wanted to set the state of where the 2nd level key was stored in a variable.
e.g. this.setState({permissions[perm.code]: e.target.checked})
However this isn't valid syntax.
I used the following code to achieve this:
this.setState({
permissions: {
...this.state.permissions,
[perm.code]: e.target.checked
}
});
You could only convert a JSON array into a CSV file.
Lets say, you have a JSON like the following :
{"infile": [{"field1": 11,"field2": 12,"field3": 13},
{"field1": 21,"field2": 22,"field3": 23},
{"field1": 31,"field2": 32,"field3": 33}]}
Lets see the code for converting it to csv :
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSON2CSV {
public static void main(String myHelpers[]){
String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";
JSONObject output;
try {
output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray("infile");
File file=new File("/tmp2/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now you got the CSV generated from JSON.
It should look like this:
field1,field2,field3
11,22,33
21,22,23
31,32,33
The maven dependency was like,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
Update Dec 13, 2019:
Updating the answer, since now we can support complex JSON Arrays as well.
import java.nio.file.Files;
import java.nio.file.Paths;
import com.github.opendevl.JFlat;
public class FlattenJson {
public static void main(String[] args) throws Exception {
String str = new String(Files.readAllBytes(Paths.get("path_to_imput.json")));
JFlat flatMe = new JFlat(str);
//get the 2D representation of JSON document
flatMe.json2Sheet().headerSeparator("_").getJsonAsSheet();
//write the 2D representation in csv format
flatMe.write2csv("path_to_output.csv");
}
}
dependency and docs details are in link
First I created the user using :
CREATE user user@localhost IDENTIFIED BY 'password_txt';
After Googling and seeing this, I updated user's password using :
SET PASSWORD FOR 'user'@'localhost' = PASSWORD('password_txt');
and I could connect afterward.
if you are running nvm you might want to run nvm use <desired-node-version>
This keeps node consistent with npm
The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.
.text-input {
-fx-text-fill: -fx-text-inner-color;
-fx-highlight-fill: derive(-fx-control-inner-background,-20%);
-fx-highlight-text-fill: -fx-text-inner-color;
-fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: 0, 1;
-fx-background-radius: 3, 2;
-fx-cursor: text;
-fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
-fx-highlight-fill: -fx-accent;
-fx-highlight-text-fill: white;
-fx-background-color:
-fx-focus-color,
-fx-control-inner-background,
-fx-faint-focus-color,
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: -0.2, 1, -1.4, 3;
-fx-background-radius: 3, 2, 4, 0;
-fx-prompt-text-fill: transparent;
}
Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:
textField.setStyle("-fx-text-inner-color: red;");
Java7 update 45 64 bit direct download link is:
http://javadl.sun.com/webapps/download/AutoDL?BundleId=81821
As previously mentioned, the bundler version may be too high for your version of rails.
I ran into the same problem using Rails 3.0.1 which requires Bundler v1.0.0 - v1.0.22
Check your bundler version using: gem list bundler
If your bundler version is not within the appropriate range, I found this solution to work: rvm @global do gem uninstall bundler
Note: rvm is required for this solution... another case for why you should be using rvm in the first place.
I use them sparingly, but they can be pretty convenient:
def log(msg):
log.logfile.write(msg)
Now I can use log
throughout my module, and redirect output simply by setting log.logfile
. There are lots and lots of other ways to accomplish that, but this one's lightweight and dirt simple. And while it smelled funny the first time I did it, I've come to believe that it smells better than having a global logfile
variable.
Slot free in NPOI excel indexedcolors from 57+
Color selColor;
var wb = new HSSFWorkbook();
var sheet = wb.CreateSheet("NPOI");
var style = wb.CreateCellStyle();
var font = wb.CreateFont();
var palette = wb.GetCustomPalette();
short indexColor = 57;
palette.SetColorAtIndex(indexColor, (byte)selColor.R, (byte)selColor.G, (byte)selColor.B);
font.Color = palette.GetColor(indexColor).Indexed;
Usually this region should contains the constructors of the class
I could not get anything to work I ended up just using powershell to start bat scripts .. sometimes even start cmd /c does not work not sure why .. I even tried stuff like start cmd /c notepad & exit
start-Process "c:\BACKUP\PRIVATE\MobaXterm_Portable\MobaXterm_Portable.bat" -WindowStyle Hidden
I got here searching for a way to execute some code whenever the program ends.
Found this:
Kernel.at_exit { puts "sayonara" }
# do whatever
# [...]
# call #exit or #abort or just let the program end
# calling #exit! will skip the call
Called multiple times will register multiple handlers.
dgv.Columns[0].HeaderText = "Your Header";
The following is my solutions which works ( 5 steps )
Step1: Add an observer to catch which UITEXTFIELD or UITEXTVIEW ShoudBeginEditing ( where object is inited or ViewDidLoad.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updateActiveField:)
name:@"UPDATE_ACTIVE_FIELD" object:nil];
Step2: Post a notification when ..ShouldBeginEditing with OBJECT of UITEXTFIELD or UITEXTVIEW
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {
[[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATE_ACTIVE_FIELD"
object:textView];
return YES;
}
Step3: The method that (Step1 calles ) assigns the current UITEXTFIELD or UITEXTVIEW
-(void) updateActiveField: (id) sender {
activeField = [sender object];
}
Step4: Add Keyboard observer UIKeyboardWillShowNotification ( same place as Step1 )
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
and method:
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
_currentEdgeInsets = self.layoutPanel.contentInset; // store current insets to restore them later
self.layoutPanel.contentInset = contentInsets;
self.layoutPanel.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
CGPoint p = [activeField convertPoint:activeField.bounds.origin toView:window];
if (!CGRectContainsPoint(aRect, p) ) {
CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y +kbSize.height);
[self.layoutPanel setContentOffset:scrollPoint animated:YES];
self.layoutPanel.scrollEnabled = NO;
}
}
Step5: Add Keyboard observer UIKeyboardWillHideNotification ( same place as step 1 )
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
and method:
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
self.layoutPanel.contentInset = _currentEdgeInsets;
self.layoutPanel.scrollIndicatorInsets = _currentEdgeInsets;
self.layoutPanel.scrollEnabled = YES;
}
Remember to remove observers!
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
similar to @python-starter solution. But, commands package is not avilable on python3.x. So Alternative solution is to use subprocess in python3.x
import subprocess
cmd = "hive -S -e 'SELECT * FROM db_name.table_name LIMIT 1;' "
status, output = subprocess.getstatusoutput(cmd)
if status == 0:
print(output)
else:
print("error")
you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual
$('input[type="text"]').get().some(item => item.value !== '');
To get the content of a url:
try: # Try importing requests first.
import requests
except ImportError:
try: # Try importing Python3 urllib
import urllib.request
except AttributeError: # Now importing Python2 urllib
import urllib
def get_content(url):
try: # Using requests.
return requests.get(url).content # Returns requests.models.Response.
except NameError:
try: # Using Python3 urllib.
with urllib.request.urlopen(index_url) as response:
return response.read() # Returns http.client.HTTPResponse.
except AttributeError: # Using Python3 urllib.
return urllib.urlopen(url).read() # Returns an instance.
It's hard to write Python2 and Python3 and request
dependencies code for the responses because they urlopen()
functions and requests.get()
function return different types:
urllib.request.urlopen()
returns a http.client.HTTPResponse
urllib.urlopen(url)
returns an instance
request.get(url)
returns a requests.models.Response
First do a:
git remote rm origin
then
git remote add origin https://github.com/your_user/your_app.git
and voila! Worked for me!
Here is the JSfiddle Demo
I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order
so you can check if it's greater than zero:
<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p>
function verifyorder() {
var order = document.getElementById('value').value;
if (+order > 0) {
alert(+order);
return true;
}
else {
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
}
}
Because on the second loop, $v
is still a reference to the last array item, so it's overwritten each time.
You can see it like that:
$a = array ('zero','one','two', 'three');
foreach ($a as &$v) {
}
foreach ($a as $v) {
echo $v.'-'.$a[3].PHP_EOL;
}
As you can see, the last array item takes the current loop value: 'zero', 'one', 'two', and then it's just 'two'... : )
This is your array
products: any = [
{
"name": "John-Cena",
},
{
"name": "Brock-Lensar",
}
];
This is your ngFor loop Filter By :
<input type="text" [(ngModel)]='filterText' />
<ul *ngFor='let product of filterProduct'>
<li>{{product.name }}</li>
</ul>
There I'm using filterProduct instant of products, because i want to preserve my original data. Here model _filterText is used as a input box.When ever there is any change setter function will call. In setFilterText performProduct is called it will return the result only those who match with the input. I'm using lower case for case insensitive.
filterProduct = this.products;
_filterText : string;
get filterText() : string {
return this._filterText;
}
set filterText(value : string) {
this._filterText = value;
this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;
}
performProduct(value : string ) : any {
value = value.toLocaleLowerCase();
return this.products.filter(( products : any ) =>
products.name.toLocaleLowerCase().indexOf(value) !== -1);
}