Start here http://docs.python.org/tutorial/datastructures.html#dictionaries
Then here http://docs.python.org/library/stdtypes.html#mapping-types-dict
Then here http://docs.python.org/library/stdtypes.html#dict.get
characters.get( key, default )
key is a character
default is 0
If the character is in the dictionary, characters
, you get the dictionary object.
If not, you get 0.
Syntax:
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to
None
, so that this method never raises aKeyError
.
I would think Eigenface, which you are doing already, is the way to go if you want to calculate the distance between faces. You could try out different approaches like Support Vector Machine or Hidden Markov Model. I found a page that lists major algorithms that could be used for facial recognition: Face Recognition Homepage.
Also, when you say "better performance," do you mean speed or accuracy? What kind of problem are you having? How varying are the data? Are they mostly frontal face or do they include profiles?
You can get these parameter list in ControllerContext.RoutValues object as key-value pair.
You can store it in some variable and you make use of that variable in your logic.
WARNING: Not for git newbies.
This comes up enough in my workflow that I've almost tried to write a new git command for it. The usual git stash
flow is the way to go but is a little awkward. I usually make a new commit first since if I have been looking at the changes, all the information is fresh in my mind and it's better to just start git commit
-ing what I found (usually a bugfix belonging on master that I discover while working on a feature branch) right away.
It is also helpful—if you run into situations like this a lot—to have another working directory alongside your current one that always have the
master
branch checked out.
So how I achieve this goes like this:
git commit
the changes right away with a good commit message.git reset HEAD~1
to undo the commit from current branch.Sometimes later (asynchronously), or immediately in another terminal window:
cd my-project-master
which is another WD sharing the same .git
git reflog
to find the bugfix I've just made.git cherry-pick SHA1
of the commit.Optionally (still asynchronous) you can then rebase (or merge) your feature branch to get the bugfix, usually when you are about to submit a PR and have cleaned your feature branch and WD already:
cd my-project
which is the main WD I'm working on.git rebase master
to get the bugfixes.This way I can keep working on the feature uninterrupted and not have to worry about git stash
-ing anything or having to clean my WD before a git checkout
(and then having the check the feature branch backout again.) and still have all my bugfixes goes to master
instead of hidden in my feature branch.
IMO git stash
and git checkout
is a real PIA when you are in the middle of working on some big feature.
If you use has_many through, and want to alias:
has_many :alias_name, through: model_name, source: initial_name
Try This :-
set Read Only False ( Editable TextBox)
document.getElementById("txtID").readOnly=false;
set Read Only true(Not Editable )
var v1=document.getElementById("txtID");
v1.setAttribute("readOnly","true");
This can work on IE and Firefox also.
Did you try:
execBtn.setAttribute("onclick", function() { runCommand() });
I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:
public Integer getId() { return id; }
public void setId(Integer i){ id= i; }
In C++0x/11 we get std::begin
and std::end
which are overloaded for arrays:
#include <algorithm>
int main(){
int v[2000];
std::sort(std::begin(v), std::end(v));
}
If you don't have access to C++0x, it isn't hard to write them yourself:
// for container with nested typedefs, non-const version
template<class Cont>
typename Cont::iterator begin(Cont& c){
return c.begin();
}
template<class Cont>
typename Cont::iterator end(Cont& c){
return c.end();
}
// const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c){
return c.begin();
}
template<class Cont>
typename Cont::const_iterator end(Cont const& c){
return c.end();
}
// overloads for C style arrays
template<class T, std::size_t N>
T* begin(T (&arr)[N]){
return &arr[0];
}
template<class T, std::size_t N>
T* end(T (&arr)[N]){
return arr + N;
}
You should use $scope.$apply() when you execute an angular expression from outside of the angular framework.
function countController($scope){
$scope.countDown = 10;
var timer = setInterval(function(){
$scope.countDown--;
$scope.$apply();
console.log($scope.countDown);
}, 1000);
}
Suppose there are 3 non-negative integers: a
, b
, and c
. Mathematically speaking, if we want to determine if c
is between a
and b
, inclusively, one can use this formula:
(c - a) * (b - c) >= 0
or in Python:
> print((c - a) * (b - c) >= 0)
True
Use substring
String strOut = "abcdefghijklmnopqrtuvwxyz"
String result = strOut.substring(0, 8) + "...";// count start in 0 and 8 is excluded
System.out.pritnln(result);
Note: substring(int first, int second) takes two parameters. The first is inclusive and the second is exclusive.
You can use fs.stat
to check if target is a file or directory and you can use fs.access
to check if you can write/read/execute the file. (remember to use path.resolve
to get full path for the target)
Documentation:
Full example (TypeScript)
import * as fs from 'fs';
import * as path from 'path';
const targetPath = path.resolve(process.argv[2]);
function statExists(checkPath): Promise<fs.Stats> {
return new Promise((resolve) => {
fs.stat(checkPath, (err, result) => {
if (err) {
return resolve(undefined);
}
return resolve(result);
});
});
}
function checkAccess(checkPath: string, mode: number = fs.constants.F_OK): Promise<boolean> {
return new Promise((resolve) => {
fs.access(checkPath, mode, (err) => {
resolve(!err);
});
});
}
(async function () {
const result = await statExists(targetPath);
const accessResult = await checkAccess(targetPath, fs.constants.F_OK);
const readResult = await checkAccess(targetPath, fs.constants.R_OK);
const writeResult = await checkAccess(targetPath, fs.constants.W_OK);
const executeResult = await checkAccess(targetPath, fs.constants.X_OK);
const allAccessResult = await checkAccess(targetPath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);
if (result) {
console.group('stat');
console.log('isFile: ', result.isFile());
console.log('isDir: ', result.isDirectory());
console.groupEnd();
}
else {
console.log('file/dir does not exist');
}
console.group('access');
console.log('access:', accessResult);
console.log('read access:', readResult);
console.log('write access:', writeResult);
console.log('execute access:', executeResult);
console.log('all (combined) access:', allAccessResult);
console.groupEnd();
process.exit(0);
}());
You can do it on a per file basis. Use the path attribute to include the filename
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="YourFileNameHere.xml">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>
With modern git you always fetch all branches (as remote-tracking branches into refs/remotes/origin/*
namespace, visible with git branch -r
or git remote show origin
).
By default (see documentation of push.default
config variable) you push matching branches, which means that first you have to do git push origin branch
for git to push it always on git push
.
If you want to always push all branches, you can set up push refspec. Assuming that the remote is named origin
you can either use git config:
$ git config --add remote.origin.push '+refs/heads/*:refs/heads/*'
$ git config --add remote.origin.push '+refs/tags/*:refs/tags/*'
or directly edit .git/config
file to have something like the following:
[remote "origin"] url = [email protected]:/srv/git/repo.git fetch = +refs/heads/*:refs/remotes/origin/* fetch = +refs/tags/*:refs/tags/* push = +refs/heads/*:refs/heads/* push = +refs/tags/*:refs/tags/*
public class DayFlipper extends ViewPager {
private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {
@Override
public int getCount() {
return DayFlipper.DAY_HISTORY;
}
@Override
public void startUpdate(View container) {
}
@Override
public Object instantiateItem(View container, int position) {
Log.d(TAG, "instantiateItem(): " + position);
Date d = DateHelper.getBot();
for (int i = 0; i < position; i++) {
d = DateHelper.getTomorrow(d);
}
d = DateHelper.normalize(d);
CubbiesView cv = new CubbiesView(mContext);
cv.setLifeDate(d);
((ViewPager) container).addView(cv, 0);
// add map
cv.setCubbieMap(mMap);
cv.initEntries(d);
adpter = FlipperAdapter.this;
return cv;
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((CubbiesView) object);
}
@Override
public void finishUpdate(View container) {
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((CubbiesView) object);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
}
...
public void refresh() {
adapter().notifyDataSetChanged();
}
}
try this.
I use both to create an Inversion Of Control strategy with more readability for developers who need to maintain it after me.
I use a Factory to create my different Layer objects (Business, Data Access).
ICarBusiness carBusiness = BusinessFactory.CreateCarBusiness();
Another developer will see this and when creating an Business Layer object he looks in BusinessFactory and Intellisense gives the developer all the possible Business Layers to create. Doesn't have to play the game, find the Interface I want to create.
This structure is already Inversion Of Control. I am no longer responsible for creating the specific object. But you still need to ensure Dependency Injection to be able to change things easily. Creating your own custom Dependency Injection is ridiculous, so I use Unity. Within the CreateCarBusiness() I ask Unity to Resolve which class belongs to this and it’s lifetime.
So my code Factory Dependency Injection structure is:
public static class BusinessFactory
{
public static ICarBusiness CreateCarBusiness()
{
return Container.Resolve<ICarBusiness>();
}
}
Now I have the benefit of both. My code is also more readable for other developers as towards scopes of my objects I use, instead of Constructor Dependency Injection which just says every object is available when the class is created.
I use this to change my Database Data Access to a custom coded Data Access layer when I create Unit Tests. I don’t want my Unit Tests to communicate with databases, webservers, e-mail servers etc. They need to test my Business Layer because that’s where the intelligence is.
This line looks suspicious:
invaders[i] = inv;
You're never incrementing i
, so you keep assigning to invaders[0]
. If this is just an error you made when reducing your code to the example, check how you calculate i
in the real code; you could be exceeding the size of invaders
.
If as your comment suggests, you're creating 55 invaders
, then check that invaders
has been initialised correctly to handle this number.
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub
Yes. 'Z' stands for Zulu time, which is also GMT and UTC.
From http://en.wikipedia.org/wiki/Coordinated_Universal_Time:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.
Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.
From wikipedia again, http://en.wikipedia.org/wiki/Nautical_time:
Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.
This is how you add jar files from external folders
1) Click on File and there you click on New and New Module
2) New Window appears ,,There you have to choose the Import .JAR/.AAR package .
3) Click on the path option at the top right corner of the window ...And give the whole path of the JAR file .
4)click on finish.
Now you have added the Jar file and You need to add it in the dependency for your application project
1)Right click on app folder and there you have to choose Open Module Settings or F4
2)Click on dependency at the top right corner of the current window .
3)Click on '+' symbol and choose 'Module Dependency' and It will show you the existed JAR files which you have included in your project ...
Choose the one you want and click 'OK/Finish'
Thank you
You can use python3 -m pip
as a synonym for pip3
. That has saved me a couple of times.
The difference between "" and () is:
With "" you are not calling anything.
With () you are calling a sub.
Example with sub:
Sub = MsgBox("Msg",vbYesNo,vbCritical,"Title")
Select Case Sub
Case = vbYes
MsgBox"You said yes"
Case = vbNo
MsgBox"You said no"
End Select
vs Normal:
MsgBox"This is normal"
According to the manual, in CPython id()
is the actual memory address of the variable. If you want it in hex format, call hex()
on it.
x = 5
print hex(id(x))
this will print the memory address of x.
There is nothing special about <input type="hidden">
:
$('input[type="hidden"]').val()
Use "$@"
to represent all the arguments:
for var in "$@"
do
echo "$var"
done
This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:
sh test.sh 1 2 '3 4'
1
2
3 4
Enabling Tracing may be a better alternative to the Windows Event Log. This gave me the information I needed to fix my own WebService.
You can solve it by making the iframe in javascript
document.write(" <iframe id='frame' name='frame' src='" + srcstring + "' width='600' height='315' allowfullscreen></iframe>");
_x000D_
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RemoveAt = gvr.RowIndex;
DataTable dt = new DataTable();
dt = (DataTable)ViewState["Products"];
dt.Rows.RemoveAt(RemoveAt);
dt.AcceptChanges();
ViewState["Products"] = dt;
}
}
catch (Exception ex)
{
throw;
}
}
protected void gvProductsList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
gvProductsList.DataSource = ViewState["Products"];
gvProductsList.DataBind();
}
catch (Exception ex)
{
}
}
You can!!! In short use this as the connection string:
ldap://<host>:3268/DC=<my>,DC=<domain>?cn
together with your search filter, e.g.
(&(sAMAccountName={0})(&((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=<some-special-nested-group>,OU=<ou3>,OU=<ou2>,OU=<ou1>,DC=<dc3>,DC=<dc2>,DC=<dc1>))))
That will search in the so called Global Catalog, that had been available out-of-the-box in our environment.
Instead of the known/common other versions (or combinations thereof) that did NOT work in our environment with multiple OUs:
ldap://<host>/DC=<my>,DC=<domain>
ldap://<host>:389/DC=<my>,DC=<domain> (standard port)
ldap://<host>/OU=<someOU>,DC=<my>,DC=<domain>
ldap://<host>/CN=<someCN>,DC=<my>,DC=<domain>
ldap://<host>/(|(OU=<someOU1>)(OU=<someOU2>)),DC=<my>,DC=<domain> (search filters here shouldn't work at all by definition)
(I am a developer, not an AD/LDAP guru:) Damn I had been searching for this solution everywhere for almost 2 days and almost gave up, getting used to the thought I might have to implement this obviously very common scenario by hand (with Jasperserver/Spring security(/Tomcat)). (So this shall be a reminder if somebody else or me should have this problem again in the future :O) )
Here some other related threads I found during my research that had been mostly of little help:
And here I will provide our anonymized Tomcat LDAP config in case it may be helpful
(/var/lib/tomcat7/webapps/jasperserver/WEB-INF/applicationContext-externalAUTH-LDAP.xml
):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- ############ LDAP authentication ############ - Sample configuration
of external authentication via an external LDAP server. -->
<bean id="proxyAuthenticationProcessingFilter"
class="com.jaspersoft.jasperserver.api.security.externalAuth.BaseAuthenticationProcessingFilter">
<property name="authenticationManager">
<ref local="ldapAuthenticationManager" />
</property>
<property name="externalDataSynchronizer">
<ref local="externalDataSynchronizer" />
</property>
<property name="sessionRegistry">
<ref bean="sessionRegistry" />
</property>
<property name="internalAuthenticationFailureUrl" value="/login.html?error=1" />
<property name="defaultTargetUrl" value="/loginsuccess.html" />
<property name="invalidateSessionOnSuccessfulAuthentication"
value="true" />
<property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>
<bean id="proxyAuthenticationSoapProcessingFilter"
class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationSoapProcessingFilter">
<property name="authenticationManager" ref="ldapAuthenticationManager" />
<property name="externalDataSynchronizer" ref="externalDataSynchronizer" />
<property name="invalidateSessionOnSuccessfulAuthentication"
value="true" />
<property name="migrateInvalidatedSessionAttributes" value="true" />
<property name="filterProcessesUrl" value="/services" />
</bean>
<bean id="proxyRequestParameterAuthenticationFilter"
class="com.jaspersoft.jasperserver.war.util.ExternalRequestParameterAuthenticationFilter">
<property name="authenticationManager">
<ref local="ldapAuthenticationManager" />
</property>
<property name="externalDataSynchronizer" ref="externalDataSynchronizer" />
<property name="authenticationFailureUrl">
<value>/login.html?error=1</value>
</property>
<property name="excludeUrls">
<list>
<value>/j_spring_switch_user</value>
</list>
</property>
</bean>
<bean id="proxyBasicProcessingFilter"
class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalAuthBasicProcessingFilter">
<property name="authenticationManager" ref="ldapAuthenticationManager" />
<property name="externalDataSynchronizer" ref="externalDataSynchronizer" />
<property name="authenticationEntryPoint">
<ref local="basicProcessingFilterEntryPoint" />
</property>
</bean>
<bean id="proxyAuthenticationRestProcessingFilter"
class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationRestProcessingFilter">
<property name="authenticationManager">
<ref local="ldapAuthenticationManager" />
</property>
<property name="externalDataSynchronizer">
<ref local="externalDataSynchronizer" />
</property>
<property name="filterProcessesUrl" value="/rest/login" />
<property name="invalidateSessionOnSuccessfulAuthentication"
value="true" />
<property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>
<bean id="ldapAuthenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<list>
<ref local="ldapAuthenticationProvider" />
<ref bean="${bean.daoAuthenticationProvider}" />
<!--anonymousAuthenticationProvider only needed if filterInvocationInterceptor.alwaysReauthenticate
is set to true <ref bean="anonymousAuthenticationProvider"/> -->
</list>
</property>
</bean>
<bean id="ldapAuthenticationProvider"
class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
<constructor-arg>
<bean
class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
<constructor-arg>
<ref local="ldapContextSource" />
</constructor-arg>
<property name="userSearch" ref="userSearch" />
</bean>
</constructor-arg>
<constructor-arg>
<bean
class="org.springframework.security.ldap.populator.DefaultLdapAuthoritiesPopulator">
<constructor-arg index="0">
<ref local="ldapContextSource" />
</constructor-arg>
<constructor-arg index="1">
<value></value>
</constructor-arg>
<property name="groupRoleAttribute" value="cn" />
<property name="convertToUpperCase" value="true" />
<property name="rolePrefix" value="ROLE_" />
<property name="groupSearchFilter"
value="(&(member={0})(&(objectCategory=Group)(objectclass=group)(cn=my-nested-group-name)))" />
<property name="searchSubtree" value="true" />
<!-- Can setup additional external default roles here <property name="defaultRole"
value="LDAP"/> -->
</bean>
</constructor-arg>
</bean>
<bean id="userSearch"
class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<constructor-arg index="0">
<value></value>
</constructor-arg>
<constructor-arg index="1">
<value>(&(sAMAccountName={0})(&((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=my-nested-group-name,OU=ou3,OU=ou2,OU=ou1,DC=dc3,DC=dc2,DC=dc1))))
</value>
</constructor-arg>
<constructor-arg index="2">
<ref local="ldapContextSource" />
</constructor-arg>
<property name="searchSubtree">
<value>true</value>
</property>
</bean>
<bean id="ldapContextSource"
class="com.jaspersoft.jasperserver.api.security.externalAuth.ldap.JSLdapContextSource">
<constructor-arg value="ldap://myhost:3268/DC=dc3,DC=dc2,DC=dc1?cn" />
<!-- manager user name and password (may not be needed) -->
<property name="userDn" value="CN=someuser,OU=ou4,OU=1,DC=dc3,DC=dc2,DC=dc1" />
<property name="password" value="somepass" />
<!--End Changes -->
</bean>
<!-- ############ LDAP authentication ############ -->
<!-- ############ JRS Synchronizer ############ -->
<bean id="externalDataSynchronizer"
class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalDataSynchronizerImpl">
<property name="externalUserProcessors">
<list>
<ref local="externalUserSetupProcessor" />
<!-- Example processor for creating user folder -->
<!--<ref local="externalUserFolderProcessor"/> -->
</list>
</property>
</bean>
<bean id="abstractExternalProcessor"
class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.AbstractExternalUserProcessor"
abstract="true">
<property name="repositoryService" ref="${bean.repositoryService}" />
<property name="userAuthorityService" ref="${bean.userAuthorityService}" />
<property name="tenantService" ref="${bean.tenantService}" />
<property name="profileAttributeService" ref="profileAttributeService" />
<property name="objectPermissionService" ref="objectPermissionService" />
</bean>
<bean id="externalUserSetupProcessor"
class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserSetupProcessor"
parent="abstractExternalProcessor">
<property name="userAuthorityService">
<ref bean="${bean.internalUserAuthorityService}" />
</property>
<property name="defaultInternalRoles">
<list>
<value>ROLE_USER</value>
</list>
</property>
<property name="organizationRoleMap">
<map>
<!-- Example of mapping customer roles to JRS roles -->
<entry>
<key>
<value>ROLE_MY-NESTED-GROUP-NAME</value>
</key>
<!-- JRS role that the <key> external role is mapped to -->
<value>ROLE_USER</value>
</entry>
</map>
</property>
</bean>
<!--bean id="externalUserFolderProcessor" class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserFolderProcessor"
parent="abstractExternalProcessor"> <property name="repositoryService" ref="${bean.unsecureRepositoryService}"/>
</bean -->
<!-- ############ JRS Synchronizer ############ -->
Checkbox Group
var group_=(el,callback)=>{
el.forEach((checkbox)=>{
callback(checkbox)
})
}
group_(document.getElementsByName('check'),(item)=>{
item.onclick=(e)=>{
group_(document.getElementsByName('check'),(item)=>{
item.checked=false;
})
e.target.checked=true;
}
})
_x000D_
<input type="checkbox" name="check" >
<input type="checkbox" name="check" >
<input type="checkbox" name="check" >
<input type="checkbox" name="check">
_x000D_
checkbox simple without loop
var last;
document.addEventListener('input',(e)=>{
if(e.target.getAttribute('name')=="myRadios"){
if(last)
last.checked=false;
}
e.target.checked=true;
last=e.target;
})
_x000D_
<input type="checkbox" name="myRadios" value="1" /> 1
<input type="checkbox" name="myRadios" value="2" /> 2
_x000D_
Group By Single Div
var group_=(el,callback)=>{
el.forEach((checkbox)=>{
callback(checkbox)
})
}
var group_el=document.querySelectorAll("*[data-name] > input")
group_(group_el,(item)=>{
item.onclick=(e)=>{
group_(group_el,(item)=>{
item.checked=false;
})
e.target.checked=true;
}
})
_x000D_
<div data-name="check">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
_x000D_
css single group div
var last;
document.addEventListener('input',(e)=>{
var closest=e.target.closest("*[data-name='check']");
console.log(closest)
if(e.target.closest("*[data-name]")){
if(last)
last.checked=false;
}
e.target.checked=true;
last=e.target;
})
_x000D_
<div data-name="check">
<input type="checkbox" value="1" /> 1
<input type="checkbox" value="2" /> 2
</div>
_x000D_
var last;
document.addEventListener('input',(e)=>{
var closest=e.target.closest("*[data-name='check']");
if(e.target.closest("*[data-name]")){
if(last)
last.checked=false;
}
if(e.target!==last)
last=e.target;
else
last=undefined;
})
_x000D_
<div data-name="check">
<input type="checkbox" value="1" /> 1
<input type="checkbox" value="2" /> 2
</div>
_x000D_
You can do this:
([0-9]+) (\([^)]+\))? Z
This will not work with nested parens for Y, however. Nesting requires recursion which isn't strictly regular any more (but context-free). Modern regexp engines can still handle it, albeit with some difficulties (back-references).
You can use the following code:
(myvar instanceof Date) // returns true or false
You can add and remove a special CSS class and modify the input value onfocus
/onblur
with JavaScript:
<input type="text" class="hint" value="Search..."
onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">
Then specify a hint class with the styling you want in your CSS for example:
input.hint {
color: grey;
}
Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):
erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"
erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"
erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"
erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"
@rem Clear IE cache - (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"
@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"
@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"
pause
I am pretty sure it will run for some time when you first run it :) Enjoy!
Use COALESCE
to avoid that outcome.
SELECT COALESCE(SUM(column),0)
FROM table
WHERE ...
To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0
More Information:
Given three tables (one with all numbers, one with all nulls, and one with a mixture):
MySQL 5.5.32 Schema Setup:
CREATE TABLE foo
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);
CREATE TABLE bar
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);
CREATE TABLE baz
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
val INT
);
INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);
Query 1:
SELECT 'foo' as table_name,
'mixed null/non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM foo
UNION ALL
SELECT 'bar' as table_name,
'all non-null' as description,
21 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM bar
UNION ALL
SELECT 'baz' as table_name,
'all null' as description,
0 as expected_sum,
COALESCE(SUM(val), 0) as actual_sum
FROM baz
| TABLE_NAME | DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
| foo | mixed null/non-null | 21 | 21 |
| bar | all non-null | 21 | 21 |
| baz | all null | 0 | 0 |
If you want to manually clean it up, for me with my version of jenkins (didn't appear to need an extra plugin installed, but who knows), there is a "workspace" link on the left column, click on your project, then on "workspace", then a "Wipe out current workspace" link appears beneath it on the left hand side column.
Fully async version with ES6, only native packages, fs.promises and async/await, does file operations in parallel:
const fs = require('fs');
const path = require('path');
async function listDirectories(rootPath) {
const fileNames = await fs.promises.readdir(rootPath);
const filePaths = fileNames.map(fileName => path.join(rootPath, fileName));
const filePathsAndIsDirectoryFlagsPromises = filePaths.map(async filePath => ({path: filePath, isDirectory: (await fs.promises.stat(filePath)).isDirectory()}))
const filePathsAndIsDirectoryFlags = await Promise.all(filePathsAndIsDirectoryFlagsPromises);
return filePathsAndIsDirectoryFlags.filter(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.isDirectory)
.map(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.path);
}
Tested, it works nicely.
The same thing happened to me with the '–' character (long minus sign).
I used this simple replace so resolve it:
htmlText = htmlText.Replace('–', '-');
Swift 5.1, Xcode 11
extension UINavigationController{
public func removePreviousController(total: Int){
let totalViewControllers = self.viewControllers.count
self.viewControllers.removeSubrange(totalViewControllers-total..<totalViewControllers - 1)
}}
Make sure to call this utility function after viewDidDisappear() of previous controller or viewDidAppear() of new controller
In order to get rid of duplicates, you can group by drinks.id
. But that way you'll get only one photo for each drinks.id
(which photo you'll get depends on database internal implementation).
Though it is not documented, in case of MySQL, you'll get the photo with lowest id
(in my experience I've never seen other behavior).
SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks.id
You have to give the values between 0 and 1.0. So divide the RGB values by 255.
myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;
Update:
You can also use this macro
#define Rgb2UIColor(r, g, b) [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]
and you can call in any of your class like this
myLabel.textColor = Rgb2UIColor(160, 97, 5);
This is the normal color synax
myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0)
//The values should be between 0 to 1
Swift is not much friendly with macros
Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.
So we use extension for this
extension UIColor {
convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
You can use it like
myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)
Here is a method that returns the image dimensions:
from PIL import Image
import os
def get_image_dimensions(imagefile):
"""
Helper function that returns the image dimentions
:param: imagefile str (path to image)
:return dict (of the form: {width:<int>, height=<int>, size_bytes=<size_bytes>)
"""
# Inline import for PIL because it is not a common library
with Image.open(imagefile) as img:
# Calculate the width and hight of an image
width, height = img.size
# calculat ethe size in bytes
size_bytes = os.path.getsize(imagefile)
return dict(width=width, height=height, size_bytes=size_bytes)
Try this out:
$url = 'http://techcrunch.com/startups/'; $url = str_replace(array('http://', 'https://'), '', $url);
EDIT:
Or, a simple way to always remove the protocol:
$url = 'https://www.google.com/'; $url = preg_replace('@^.+?\:\/\/@', '', $url);
Once you have your image, you can use
$ docker tag <image> <newName>/<repoName>:<tagName>
Build and tag the image with creack/node:latest
$ ID=$(docker build -q -t creack/node .)
Add a new tag
$ docker tag $ID creack/node:0.10.24
You can use this and skip the -t part from build
$ docker tag $ID creack/node:latest
I was also having problem with starting MySql server but run command as mention right mark in picture . Its working fine .
if you include the /
at the start of the include, the include will be taken as the path from the root of the site.
if your site is http://www.example.com/game/forum/files/index.php you can add an include to /includes/boot.inc.php which would resolve to http://www.example.com/includes/boot.inc.php .
You have to be careful with ..
traversal as some web servers have it disabled; it also causes problems when you want to move your site to a new machine/host and the structure is a little different.
The return statement
stops the execution of a function and returns a value
from that function.
While updating global variables is one way to pass information back to the code that called the function
, this is not an ideal way of doing so. A much better alternative is to write the function so that values that are used by the function are passed to it as parameters and the function returns whatever value that it needs to without using or updating any global variables
.
By limiting the way in which information is passed to and from functions we can make it easier to reuse the same function from multiple places in our code.
JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running.
JavaScript passes a value from a function back to the code that called it by using the return statement
. The value to be returned is specified in the return
keyword.
Just weighing in here with a nice solution I have been using. This is similar to Lucky Soni's solution above in that it supports aggregation, but doesn't require hard coding of the field names.
cursor = db.<collection_name>.<my_query_with_aggregation>;
headerPrinted = false;
while (cursor.hasNext()) {
item = cursor.next();
if (!headerPrinted) {
print(Object.keys(item).join(','));
headerPrinted = true;
}
line = Object
.keys(item)
.map(function(prop) {
return '"' + item[prop] + '"';
})
.join(',');
print(line);
}
Save this as a .js
file, in this case we'll call it example.js
and run it with the mongo command line like so:
mongo <database_name> example.js --quiet > example.csv
if discount.nil? || discount == 0
[do something]
end
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
My workabout: I use asynchronous requests dumping the code to a buffer. I have a loop checking the buffer every second. When the dump has arrived to the buffer I execute the code. I also use a timeout. For the end user the page works as if synchronous requests would be used.
if(---------)
printf("hello");
else
printf("hi");
Fill in the blanks so that neither hello nor hi would appear in output.
ans: fclose(stdout)
Besides the redundant )
this expression will always be true
because currentStatus
will always match one of these two conditions:
currentStatus !== 'open' || currentStatus !== 'reopen'
perhaps you mean one of
!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')
I finally discover the error. The problem is that the primary key constraint name is equal the table name. I don know how postgres represents constraints, but I think the error "Relation already exists" was being triggered during the creation of the primary key constraint because the table was already declared. But because of this error, the table wasnt created at the end.
May be a bit late but in my case i had to put the id in the 2nd anonymous object. This is because the 1st one is for route values i.e the return Url.
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { id = "signupform", role = "form" }))
Hope this can help somebody :)
To complete the answer, it could work something like this...
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
switch (types) {
case UIRemoteNotificationTypeAlert:
case UIRemoteNotificationTypeBadge:
// For enabled code
break;
case UIRemoteNotificationTypeSound:
case UIRemoteNotificationTypeNone:
default:
// For disabled code
break;
}
edit: This is not right. since these are bit-wise stuff, it wont work with a switch, so I ended using this:
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
UIRemoteNotificationType typesset = (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);
if((types & typesset) == typesset)
{
CeldaSwitch.chkSwitch.on = true;
}
else
{
CeldaSwitch.chkSwitch.on = false;
}
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
I had the same problem and I found this is working:
if ($("#deliveryNext").attr('disabled')) {
// do sth if disabled
} else {
// do sth if enabled
}
If this gives you undefined then you can use if
condition also.
When you evaluate undefined
it will return false
.
Set PYTHONPATH
environment variable in root project directory.
Considering UNIX-like:
export PYTHONPATH=.
yourDGV.Rows.Add(column1,column2...columnx); //add a row to a dataGridview
yourDGV.Rows[rowindex].Cells[Cell/Columnindex].value = yourvalue; //edit the value
you can also create a new row and then add it to the DataGridView like this:
DataGridViewRow row = new DataGridViewRow();
row.Cells[Cell/Columnindex].Value = yourvalue;
yourDGV.Rows.Add(row);
I don't know of any built in method. But, coding by hand is not too difficult. Assuming the elements of the array you are dealing with are NSNumber objects of integer type, and 'arr' is the NSMutableArray that you want to reverse.
int n = [arr count];
for (int i=0; i<n/2; ++i) {
id c = [[arr objectAtIndex:i] retain];
[arr replaceObjectAtIndex:i withObject:[arr objectAtIndex:n-i-1]];
[arr replaceObjectAtIndex:n-i-1 withObject:c];
}
Since you start with a NSArray then you have to create the mutable array first with the contents of the original NSArray ('origArray').
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr setArray:origArray];
Edit: Fixed n -> n/2 in the loop count and changed NSNumber to the more generic id due to the suggestions in Brent's answer.
Try this:
list.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
You can put set xact_abort on
before your transaction to make sure sql rolls back automatically in case of error.
Assuming you mean changing the icon shown on the home screen, this could easily be done by creating a widget that does exactly this. Here's an article that demonstrate how that can be accomplished for a "new messages" type application similar to iPhone:
Try this.
HTML
<!-- Your table -->
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>From</th>
<th>To</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" autofocus placeholder="who" name="who" ></td>
<td><input type="text" autofocus placeholder="location" name="location" ></td>
<td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
<td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
<td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
</tr>
<tbody>
</table>
<!-- Model of new row -->
<table id="new-row-model" style="display: none">
<tbody>
<tr>
<td><input type="text" autofocus placeholder="who" name="who" ></td>
<td><input type="text" autofocus placeholder="location" name="location" ></td>
<td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
<td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
<td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
</tr>
<tbody>
</table>
Script
$("input.tr_clone_add").live('click', function(){
var new_row = $("#new-row-model tbody").clone();
$("#table-data tbody").append(new_row.html());
});
The accepted answer is helpful, but it isn't immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren't so lucky, here is how it is done:
@echo off
setlocal enabledelayedexpansion enableextensions
set myPath=C:\Somewhere\Somewhere\SomeFile.txt
call :file_name_from_path result !myPath!
echo %result%
goto :eof
:file_name_from_path <resultVar> <pathVar>
(
set "%~1=%~nx2"
exit /b
)
:eof
endlocal
Now the :file_name_from_path
function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn't passed into the file at all.
This probably is not what you want but you could scrap the page for the information using the following:
document.getElementsByClassName('watch-view-count')[0].innerHTML
c is the new dictionary, and a is your original dictionary, {'z','w'} are the keys you want to remove from a
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
Also check: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)
or like posted previously
sum(l)/(len(l)*1.0)
The 1.0 is to make sure you get a floating point division
This exact functionality (3 second glow to highlight a message) is implemented in the jQuery UI as the highlight effect
https://api.jqueryui.com/highlight-effect/
Color and duration are variable
As mentioned in other answers, the ability to add implementation to an interface was added in order to provide backward compatibility in the Collections framework. I would argue that providing backward compatibility is potentially the only good reason for adding implementation to an interface.
Otherwise, if you add implementation to an interface, you are breaking the fundamental law for why interfaces were added in the first place. Java is a single inheritance language, unlike C++ which allows for multiple inheritance. Interfaces provide the typing benefits that come with a language that supports multiple inheritance without introducing the problems that come with multiple inheritance.
More specifically, Java only allows single inheritance of an implementation, but it does allow multiple inheritance of interfaces. For example, the following is valid Java code:
class MyObject extends String implements Runnable, Comparable { ... }
MyObject
inherits only one implementation, but it inherits three contracts.
Java passed on multiple inheritance of implementation because multiple inheritance of implementation comes with a host of thorny problems, which are outside the scope of this answer. Interfaces were added to allow multiple inheritance of contracts (aka interfaces) without the problems of multiple inheritance of implementation.
To support my point, here is a quote from Ken Arnold and James Gosling from the book The Java Programming Language, 4th edition:
Single inheritance precludes some useful and correct designs. The problems of multiple inheritance arise from multiple inheritance of implementation, but in many cases multiple inheritance is used to inherit a number of abstract contracts and perhaps one concrete implementation. Providing a means to inherit an abstract contract without inheriting an implementation allows the typing benefits of multiple inheritance without the problems of multiple implementation inheritance. The inheritance of an abstract contract is termed interface inheritance. The Java programming language supports interface inheritance by allowing you to declare an
interface
type
well after spending about 10 days trying to solve this issue, i finally figured it out today and decide to post the solution
in the start menu, type RUN, open it the in the run box, type SERVICES.MSC, click okay
ensure that these two services are started SQL Server(MSSQLSERVER) SQL Server Vss writer
A very good, and working, javascript solution is provided here : https://github.com/niutech/showModalDialog
I personnally used it, works like before for other browser and it creates a new dialog for chrome browser.
Here is an example on how to use it :
function handleReturnValue(returnValue) {
if (returnValue !== undefined) {
// do what you want
}
}
var myCallback = function (returnValue) { // callback for chrome usage
handleReturnValue(returnValue);
};
var returnValue = window.showModalDialog('someUrl', 'someDialogTitle', 'someDialogParams', myCallback);
handleReturnValue(returnValue); // for other browsers except Chrome
To store DataTable
in Session:
DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest;
To retrieve DataTable
from Session:
DataTable dt = (DataTable) Session["dtTest"];
One way to achieve similar effect would be through CSS:
<td>Cell content.
<div class="popup">
This is the popup.
<br>
Another line of popup.
</div>
</td>
And then use the following in CSS:
td div.popup { display: none; }
td:hover div.popup { display: block; position: absolute; }
You will want to add some borders and background to make the popup look decent, but this should sketch the idea. It has some drawbacks though, for example the popup is not positioned relative to mouse but relative to the containing cell.
set list = a1-2019 a3-2018 a4-2017
setlocal enabledelayedexpansion
set backup=
set bb1=
for /d %%d in (%list%) do (
set td=%%d
set x=!td!
set y=!td!
set y=!y:~-4!
if !y! gtr !bb1! (
set bb1=!y!
set backup=!x!
)
)
rem: backup will be 2019
echo %backup%
This should work:
User.Identity.Name
Identity
returns an IPrincipal
Here is the link to the Microsoft documentation.
find /PATH/TO/YOUR/FILES -name NAME.EXT -exec cp -rfp {} /DST_DIR \;
You just need to enable the tooltip:
$('some id or class that you add to the above a tag').popover({
trigger: "hover"
})
You have to add your jquery script to your chrome-extension project and to the background
section of your manifest.json like this :
"background":
{
"scripts": ["thirdParty/jquery-2.0.3.js", "background.js"]
}
If you need jquery in a content_scripts, you have to add it in the manifest too:
"content_scripts":
[
{
"matches":["http://website*"],
"js":["thirdParty/jquery.1.10.2.min.js", "script.js"],
"css": ["css/style.css"],
"run_at": "document_end"
}
]
This is what I did.
Also, if I recall correctly, the background scripts are executed in a background window that you can open via chrome://extensions
.
CrossAlignment.center is using the Width of the 'Child Widget'
to center itself and hence gets rendered at the start of the page.
When the Column is centered within the page body's 'Center Container'
, the CrossAlignment.center uses page body's 'Center' as reference and renders the widget at the center of the page
Code
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
title:"DynamicWidgetApp",
home:DynamicWidgetApp(),
));
class DynamicWidgetApp extends StatefulWidget{
@override
DynamicWidgetAppState createState() => DynamicWidgetAppState();
}
class DynamicWidgetAppState extends State<DynamicWidgetApp>{
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
//Removing body:Center will change the reference
// and render the widget at the start of the page
child: Column(
mainAxisAlignment : MainAxisAlignment.center,
crossAxisAlignment : CrossAxisAlignment.center,
children: [
Text("My Centered Widget"),
]
),
),
floatingActionButton: FloatingActionButton(
// onPressed: ,
child : Icon(Icons.add),
),
);
}
}
"how can i return a array in a c++ method and how must i declare it? int[] test(void); ??"
template <class X>
class Array
{
X *m_data;
int m_size;
public:
// there constructor, destructor, some methods
int Get(X* &_null_pointer)
{
if(!_null_pointer)
{
_null_pointer = new X [m_size];
memcpy(_null_pointer, m_data, m_size * sizeof(X));
return m_size;
}
return 0;
}
};
just for int
class IntArray
{
int *m_data;
int m_size;
public:
// there constructor, destructor, some methods
int Get(int* &_null_pointer)
{
if(!_null_pointer)
{
_null_pointer = new int [m_size];
memcpy(_null_pointer, m_data, m_size * sizeof(int));
return m_size;
}
return 0;
}
};
example
Array<float> array;
float *n_data = NULL;
int data_size;
if(data_size = array.Get(n_data))
{ // work with array }
delete [] n_data;
example for int
IntArray array;
int *n_data = NULL;
int data_size;
if(data_size = array.Get(n_data))
{ // work with array }
delete [] n_data;
Perl solution:
perl -ane '$maxc = $#F if $#F > $maxc; END{$maxc++; print "max columns: $maxc\nrows: $.\n"}' file
If your input file is comma-separated:
perl -F, -ane '$maxc = $#F if $#F > $maxc; END{$maxc++; print "max columns: $maxc\nrows: $.\n"}' file
output:
max columns: 5
rows: 2
-a
autosplits input line to @F
array
$#F
is the number of columns -1
-F,
field separator of , instead of whitespace
$.
is the line number (number of rows)
Seeing that this is marked as gcc you can use the command line switch Wno-unused-parameter
.
For example:
gcc -Wno-unused-parameter test.c
Of course this effects the whole file (and maybe project depending where you set the switch) but you don't have to change any code.
I assume you want to know the performance difference between the following:
WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that OR
evaluates them one by one in no particular order. So IN
is faster in some circumstances.
The best way to know is to profile both on your database with your specific data to see which is faster.
I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:
SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)
SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)
So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.
This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.
(function (angular) {
'use strict';
angular.module('uploadModule', [])
.controller('uploadCtrl', [
'$scope',
'$upload',
function ($scope, $upload) {
$scope.model = {};
$scope.selectedFile = [];
$scope.uploadProgress = 0;
$scope.uploadFile = function () {
var file = $scope.selectedFile[0];
$scope.upload = $upload.upload({
url: 'api/upload',
method: 'POST',
data: angular.toJson($scope.model),
file: file
}).progress(function (evt) {
$scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}).success(function (data) {
//do something
});
};
$scope.onFileSelect = function ($files) {
$scope.uploadProgress = 0;
$scope.selectedFile = $files;
};
}
])
.directive('progressBar', [
function () {
return {
link: function ($scope, el, attrs) {
$scope.$watch(attrs.progressBar, function (newValue) {
el.css('width', newValue.toString() + '%');
});
}
};
}
]);
}(angular));
HTML
<form ng-submit="uploadFile()">
<div class="row">
<div class="col-md-12">
<input type="text" ng-model="model.fileDescription" />
<input type="number" ng-model="model.rating" />
<input type="checkbox" ng-model="model.isAGoodFile" />
<input type="file" ng-file-select="onFileSelect($files)">
<div class="progress" style="margin-top: 20px;">
<div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
<span ng-bind="uploadProgress"></span>
<span>%</span>
</div>
</div>
<button button type="submit" class="btn btn-default btn-lg">
<i class="fa fa-cloud-upload"></i>
<span>Upload File</span>
</button>
</div>
</div>
</form>
EDIT: Added passing a model up to the server in the file post.
The form data in the input elements would be sent in the data property of the post and be available as normal form values.
@echo off cls echo press any key to continue backup ! pause xcopy c:\users\file*.* e:\backup*.* /s /e echo backup complete pause
file = name of file your wanting to copy
Hope this helps
The WordPress password hasher implements the Portable PHP password hashing framework, which is used in Content Management Systems like WordPress and Drupal.
They used to use MD5 in the older versions, but sadly for me, no more. You can generate hashes using this encryption scheme at http://scriptserver.mainframe8.com/wordpress_password_hasher.php.
what you have is fine - however to save some typing, you can simply use for your data
data: $('#formId').serialize()
see http://www.ryancoughlin.com/2009/05/04/how-to-use-jquery-to-serialize-ajax-forms/ for details, the syntax is pretty basic.
Use pipelist.exe from Sysinternals.
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
With FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
As of version 2.4 of the Maven Dependency Plugin, you can also define a target destination for the artifact by using the -Ddest flag. It should point to a filename (not a directory) for the destination artifact. See the parameter page for additional parameters that can be used
mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
-DremoteRepositories=http://download.java.net/maven/2 \
-Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT \
-Ddest=c:\temp\robo-guice.jar
Another option is to use uniqueResultOptional() method, which gives you Optional in result:
String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
Query query=em.createQuery(hql);
query.setParameter("today",new LocalDate());
Optional<DrawUnusedBalance> drawUnusedBalance=query.uniqueResultOptional();
It is about string concatenation performance. It's potentially significant if your have dense logging statements.
(Prior to SLF4J 1.7) But only two parameters are possible
Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.
For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }
. There should be few enough of them that the performance is not as important.
To add to Oleg's answer:
I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath)
to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!
* I actually don't know if the $(ExecutablePath)
macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.
If you need non-sequential guids you can send the sys_guid()
results through a hashing function (see https://stackoverflow.com/a/22534843/1462295 ). The idea is to keep whatever uniqueness is used from the original creation, and get something with more shuffled bits.
For instance:
LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32))
Example showing default sequential guid vs sending it through a hash:
SELECT LOWER(SYS_GUID()) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SYS_GUID()) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SYS_GUID()) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SYS_GUID()) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32)) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32)) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32)) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32)) AS OGUID FROM DUAL
output
80c32a4fbe405707e0531e18980a1bbb
80c32a4fbe415707e0531e18980a1bbb
80c32a4fbe425707e0531e18980a1bbb
80c32a4fbe435707e0531e18980a1bbb
c0f2ff2d3ef7b422c302bd87a4588490
d1886a8f3b4c547c28b0805d70b384f3
a0c565f3008622dde3148cfce9353ba7
1c375f3311faab15dc6a7503ce08182c
I ended up coding a custom solution (Firefox extension) that does this. I think by the time I developed it, the commandline mentioned in enreas wasn't there.
The Firefox extension is CmdShots. It's a good option if you need finer degree of control over the process of taking the screenshot (or you want to do some HTML/JS modifications and image processing).
You can use it and abuse it. I decided to keep it unlicensed, so you are free to play with it as you want.
You can use Bundle to do the same in Android
Create the intent:
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“stuff”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Now in your second activity retrieve your data from the bundle:
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString(“stuff”);
have a look at the php documentation for theese functions you can send post reqeust using them.
fsockopen()
fputs()
or simply use a class like Zend_Http_Client which is also based on socket-conenctions.
also found a neat example using google...
You could also flip your if test:
foreach ( int number in numbers )
{
if ( number >= 0 )
{
//process number
}
}
The Python documentation does explain it.
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
You can do in this in Angular with ECMAScript6 by using the spread operator:
let copy = {...myObject};
You could do something like this:
\documentclass{article}
\begin{document}
Normal:
\begin{itemize}
\item foo
\item bar
\item baz
\end{itemize}
Less space:
\begin{itemize}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
Try using the following:
Window parentWindow = Window.GetWindow(userControlReference);
The GetWindow
method will walk the VisualTree for you and locate the window that is hosting your control.
You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow
method from returning null
. E.g. wire up an event:
this.Loaded += new RoutedEventHandler(UserControl_Loaded);
Put the UNIQUE declaration within the column definition section; working example:
CREATE TABLE a (
i INT,
j INT,
UNIQUE(i, j) ON CONFLICT REPLACE
);
Simple Import os package and run below command.
import os
os.system("python test.py")
The difference between a shared project and a class library is that the latter is compiled and the unit of reuse is the assembly.
Whereas with the former, the unit of reuse is the source code, and the shared code is incorporated into each assembly that references the shared project.
This can be useful when you want to create separate assemblies that target specific platforms but still have code that should be shared.
See also here:
The shared project reference shows up under the References node in the Solution Explorer, but the code and assets in the shared project are treated as if they were files linked into the main project.
In previous versions of Visual Studio1, you could share source code between projects by Add -> Existing Item and then choosing to Link. But this was kind of clunky and each separate source file had to be selected individually. With the move to supporting multiple disparate platforms (iOS, Android, etc), they decided to make it easier to share source between projects by adding the concept of Shared Projects.
1 This question and my answer (up until now) suggest that Shared Projects was a new feature in Visual Studio 2015. In fact, they made their debut in Visual Studio 2013 Update 2
When a query takes that long, I would advice to run it asynchronously and use a callback function for when it's complete.
I don't have much experience with ASP.NET, but maybe you can use AJAX for this asynchronous behavior.
Typically a web page should load in mere seconds, not minutes. Don't keep your users waiting for so long!
You can just do:
git checkout --orphan assets
cp /where/image/currently/located/on/machine/diagram.png .
git add .
git commit -m 'Added diagram'
git push -u origin assets
Then you can just reference it in the README
file like so:
![diagram](diagram.png)
To complete Robert Brisita's bit test .
if ( ~i & 1 ) {
// Even
}
You can use AOP and Java annotations from jcabi-aspects (I'm a developer):
@RetryOnFailure(attempts = 3, delay = 5)
public String load(URL url) {
return url.openConnection().getContent();
}
You could also use @Loggable
and @LogException
annotations.
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
Perhaps the simplest solution uses one of my favorite little-known functions, strcspn()
:
buffer[strcspn(buffer, "\n")] = 0;
If you want it to also handle '\r'
(say, if the stream is binary):
buffer[strcspn(buffer, "\r\n")] = 0; // works for LF, CR, CRLF, LFCR, ...
The function counts the number of characters until it hits a '\r'
or a '\n'
(in other words, it finds the first '\r'
or '\n'
). If it doesn't hit anything, it stops at the '\0'
(returning the length of the string).
Note that this works fine even if there is no newline, because strcspn
stops at a '\0'
. In that case, the entire line is simply replacing '\0'
with '\0'
.
I dislike the ls - A
solutions posted. Most likely you wish to test if the directory is empty because you don't wish to delete it. The following does that. If however you just wish to log an empty file, surely deleting and recreating it is quicker then listing possibly infinite files?
This should work...
if ! rmdir ${target}
then
echo "not empty"
else
echo "empty"
mkdir ${target}
fi
Xcode 5 lost my Mac Provisioning Profile while the one for iOS was present. The tips elsewhere helped solve the problem; this is what I did, because I noticed the lists were too short and did not include *Mac Team Provisioning Profile: **
If you're using SQL Server, you could use SQL Server Profiler (if you have it) to view the command string that is actually executed. That would be useful for copy/paste testing purpuses but not for logging I'm afraid.
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
In the Stored Procedure create a global temporary table ##temptable and write an insert query within your stored procedure which inserts the data in your table into this temporary table.
Once this is done you can check the content of the temporary table by opening a new query window. Just use "select * from ##temptable"
It worked with ASP.NET only after adding the pragma:no-cache
header in IIS. Cache-Control: no-cache
was not enough.
Two simple solutions:
Execute your code once before the while loop
actions() {
check_if_file_present
# Do other stuff
}
actions #1st execution
while [ current_time <= $cutoff ]; do
actions # Loop execution
done
Or:
while : ; do
actions
[[ current_time <= $cutoff ]] || break
done
Try having your while loop like this:
minutes = 0
while run == "start":
current_sec = timer()
#print current_sec
if current_sec == 59:
minutes = minutes + 1
print ">>>>>>>>>>>>>>>>>>>>>", mins
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
Those are two different things, as others have mentioned.
When you specify # -*- coding: utf-8 -*-
, you're telling Python the source file you've saved is utf-8
. The default for Python 2 is ASCII (for Python 3 it's utf-8
). This just affects how the interpreter reads the characters in the file.
In general, it's probably not the best idea to embed high unicode characters into your file no matter what the encoding is; you can use string unicode escapes, which work in either encoding.
When you declare a string with a u
in front, like u'This is a string'
, it tells the Python compiler that the string is Unicode, not bytes. This is handled mostly transparently by the interpreter; the most obvious difference is that you can now embed unicode characters in the string (that is, u'\u2665'
is now legal). You can use from __future__ import unicode_literals
to make it the default.
This only applies to Python 2; in Python 3 the default is Unicode, and you need to specify a b
in front (like b'These are bytes'
, to declare a sequence of bytes).
In my case, I was getting value of <input type="text">
with JQuery and I did it like this:
var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
"firstName": inputFirstName[0] , "email": inputEmail[0].value}
And I was constantly getting this exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: java.io.PushbackInputStream@39cb6c98; line: 1, column: 54] (through reference chain: com.springboot.domain.User["firstName"]).
And I banged my head for like an hour until I realised that I forgot to write .value
after this"firstName": inputFirstName[0]
.
So, the correct solution was:
var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
"firstName": inputFirstName[0].value , "email": inputEmail[0].value}
I came here because I had this problem and I hope I save someone else hours of misery.
Cheers :)
I think the exact answer is: for api 11 or higher:
getActionBar().setDisplayShowHomeEnabled(false);
otherwise:
getSupportActionBar().setDisplayShowHomeEnabled(false);
(because it need a support library.)
'remote: error: denying non-fast-forward refs/heads/master (you should pull first)'
That message suggests that there is a hook on the server that is rejecting fast forward pushes. Yes, it is usually not recommended and is a good guard, but since you are the only person using it and you want to do the force push, contact the administrator of the repo to allow to do the non-fastforward push by temporarily removing the hook or giving you the permission in the hook to do so.
This beautiful code here creates a table with each td having array values. Not my code, but it helped me!
var rows = 6, cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
Eclipse Photon user here, found it under the toolbar's Windows > Preferences > Install/Update > "Uninstall or update" link > Click stuff and hit the "Uninstall" button.
To remove the validation summary you could write this
$('div#errorMessage').remove();
However, once you removed , again if validation failed it won't show this validation summary because you removed it. Instead use hide and display using the below code
$('div#errorMessage').css('display', 'none');
$('div#errorMessage').css('display', 'block');
You can overload the method with different parameters:
public int doSomething(int arg1, int arg2)
{
//some logic here
return 0;
}
public int doSomething(
{
doSomething(0,0)
}
Why don't you use
DbTestDataContext obj = new DbTestDataContext();
var q =from a in obj.GetTable<TableName>() select a;
This is simple.
You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com
This article describes various options for accessing SharePoint content. You have a choice between REST and CSOM. I'd try CSOM if possible. File upload / download specifically is nicely described in this article.
Overall notes:
//First construct client context, the object which will be responsible for
//communication with SharePoint:
var context = new ClientContext(@"http://site.absolute.url")
//then get a hold of the list item you want to download, for example
var list = context.Web.Lists.GetByTitle("Pipeline");
var query = CamlQuery.CreateAllItemsQuery(10000);
var result = list.GetItems(query);
//note that data has not been loaded yet. In order to load the data
//you need to tell SharePoint client what you want to download:
context.Load(result, items=>items.Include(
item => item["Title"],
item => item["FileRef"]
));
//now you get the data
context.ExecuteQuery();
//here you have list items, but not their content (files). To download file
//you'll have to do something like this:
var item = items.First();
//get the URL of the file you want:
var fileRef = item["FileRef"];
//get the file contents:
FileInformation fileInfo = File.OpenBinaryDirect(context, fileRef.ToString());
using (var memory = new MemoryStream())
{
byte[] buffer = new byte[1024 * 64];
int nread = 0;
while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
memory.Write(buffer, 0, nread);
}
memory.Seek(0, SeekOrigin.Begin);
// ... here you have the contents of your file in memory,
// do whatever you want
}
Avoid working with the stream directly, read it into the memory first. Network-bound streams are not necessarily supporting stream operations, not to mention performance. So, if you are reading a pic from that stream or parsing a document, you may end up with some unexpected behavior.
On a side note, I have a related question re: performance of this code above, as you are taking some penalty with every file request. See here. And yes, you need 4.5 full .NET profile for this.
If you do not want to the text twice as column heading as well as value, use the following stmt!
SELECT 'some text' as '';Example:
mysql>SELECT 'some text' as ''; +-----------+ | | +-----------+ | some text | +-----------+ 1 row in set (0.00 sec)
It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.
In pseudocode,
foo = bar ?: baz;
roughly resolves to
foo = bar ? bar : baz;
or
if (bar) {
foo = bar;
} else {
foo = baz;
}
with the difference that bar
will only be evaluated once.
You can also use this to do a "self-check" of foo
as demonstrated in the code example you posted:
foo = foo ?: bar;
This will assign bar
to foo
if foo
is null or falsey, else it will leave foo
unchanged.
Some more examples:
<?php
var_dump(5 ?: 0); // 5
var_dump(false ?: 0); // 0
var_dump(null ?: 'foo'); // 'foo'
var_dump(true ?: 123); // true
var_dump('rock' ?: 'roll'); // 'rock'
?>
By the way, it's called the Elvis operator.
Your NSSet
approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet
to begin with?
I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet
to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:
NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
[mutableArray removeObjectAtIndex:index];
}
index--;
}
[copy release];
The easy way is by using sprintf
. I know others have suggested itoa
, but a) it isn't part of the standard library, and b) sprintf
gives you formatting options that itoa
doesn't.
Simple, send one header location.
My site, contains one image, and after upload the image, there not change, then I add this code:
<?php header("Location: pagelocalimage.php"); ?>
Work's for me.
I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:
Hope that helps!
If you don't want to deal with the pain of the conversion every time simply create an extension method.
public static class Extensions
{
public static SolidColorBrush ToBrush(this string HexColorString)
{
return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
}
}
Then use like this: BackColor = "#FFADD8E6".ToBrush()
Alternately if you could provide a method to do the same thing.
public SolidColorBrush BrushFromHex(string hexColorString)
{
return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
}
BackColor = BrushFromHex("#FFADD8E6");
Try
SELECT TOP 10000 * FROM table ORDER BY NEWID()
Would this give the desired results, without being too over complicated?
There is also a nice web app to see the dependencies in a weighted map kind of view.
For example:
Just try to remove clear:both
property from the div
with class
sample
and see how it follows floating divs
.
According to http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
IntPtr ip = source.GetHbitmap();
BitmapSource bs = null;
try
{
bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(ip);
}
return bs;
}
It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.
image1.Source = YourUtilClass.loadBitmap(SomeBitmap);
There are 2 easy ways
step 1.Go to https://dev.twitter.com/apps
step 2.Create app(fill up the form)
step 3.Change permissions if necessary(depending if you want to just read,write or execute)
step 4.Go To API keys section and click generate ACCESS TOKEN.
5 years late to answer :)
Now you have these tokens which is all you need.
'oauth_access_token' => Access token
'oauth_access_token_secret' => Access token secret
'consumer_key' => API key
'consumer_secret' => API secret
public function testing($Url=''){
$ch = curl_init($Url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode >= 200 && $httpcode <= 301){
$this->output->set_header('Access-Control-Allow-Origin: *');
$this->output->set_content_type('application/json', 'utf-8');
$this->output->set_status_header(200);
$this->output->set_output(json_encode('VALID URL', JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return;
}else{
$this->output->set_header('Access-Control-Allow-Origin: *');
$this->output->set_content_type('application/json', 'utf-8');
$this->output->set_status_header(200);
$this->output->set_output(json_encode('INVALID URL', JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return;
}
}
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).
By default, imshow
sets the aspect of the plot to 1, as this is often what people want for image data.
In your case, you can do something like:
import matplotlib.pyplot as plt
import numpy as np
grid = np.random.random((10,10))
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))
ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')
ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')
ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')
plt.tight_layout()
plt.show()
Extending @zSkycat's answer a little, you can create a generic that accepts two object types and returns a merged type with the members of the second overriding the members of the first.
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type Merge<M, N> = Omit<M, Extract<keyof M, keyof N>> & N;
interface A {
name: string;
color?: string;
}
// redefine name to be string | number
type B = Merge<A, {
name: string | number;
favorite?: boolean;
}>;
let one: A = {
name: 'asdf',
color: 'blue'
};
// A can become B because the types are all compatible
let two: B = one;
let three: B = {
name: 1
};
three.name = 'Bee';
three.favorite = true;
three.color = 'green';
// B cannot become A because the type of name (string | number) isn't compatible
// with A even though the value is a string
// Error: Type {...} is not assignable to type A
let four: A = three;
This is a fairly trivial effect to accomplish. One way to achieve this is to simply place floated div
elements within a common parent container, and set their width and height. In order to clear the floated elements, we set the overflow
property of the parent.
<div class="container">
<div class="cube">do</div>
<div class="cube">ray</div>
<div class="cube">me</div>
<div class="cube">fa</div>
<div class="cube">so</div>
<div class="cube">la</div>
<div class="cube">te</div>
<div class="cube">do</div>
</div>
The CSS resembles the strategy outlined in the first paragraph above:
.container {
width: 450px;
overflow: auto;
}
.cube {
float: left;
width: 150px;
height: 150px;
}
You can see the end result here: http://jsfiddle.net/Qjum2/2/
Browsers that support pseudo elements provide an alternative way to clear:
.container::after {
content: "";
clear: both;
display: block;
}
You can see the results here: http://jsfiddle.net/Qjum2/3/
I hope this helps.
The better way is using 'background-size'.
.pnx-msg-icon .pnx-icon-msg-warning{
background-image: url("../pics/edit.png");
background-repeat: no-repeat;
background-size: 10px;
width: 10px;
height: 10px;
cursor: pointer;
}
even if your icon dimensions is bigger than 10px it will be 10px.
In python this work for me
self.set_your_value = "your value"
def your_method_name(self):
self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`
I'm constantly running into this problem. Make sure you set git --config user.name "" and not your real name, which I've done a few times..
I tried all the above things, and still ng as sticking around globally. So in powershell I ran Get-Command ng
, and then it became clear what my problem was. I was using yarn heavily in the past, and all the old angular cli packages were also installed globally in the yarn cache location. I deleted my yarn cache for good measure, but probably could have just updated the global angular cli via yarn. In any case, I hope this helps remind some of you that if you use yarn, then global commands like ng can also live in another path than where npm puts them.
Just write what you really wanted to know:
fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")
It's much simpler than anything with substring.
Simply use the .rules('add')
method immediately after creating the element...
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
// create the new input element
$('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
// declare the rule on this newly created input field
$('#FileUpload' + filenumber).rules('add', {
required: true, // <- with this you would not need 'required' attribute on input
accept: "image/jpeg, image/pjpeg"
});
filenumber++; // increment counter for next time
return false;
});
You'll still need to use .validate()
to initialize the plugin within a DOM ready handler.
You'll still need to declare rules for your static elements using .validate()
. Whatever input elements that are part of the form when the page loads... declare their rules within .validate()
.
You don't need to use .each()
, when you're only targeting ONE element with the jQuery selector attached to .rules()
.
You don't need the required
attribute on your input element when you're declaring the required
rule using .validate()
or .rules('add')
. For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required"
.
Working DEMO: http://jsfiddle.net/8dAU8/5/
I know this is an older issue, but I recently had the same problem and was having issues resolving it, despite attempting the DisplayUnlockCaptcha fix. This is how I got it alive.
Head over to Account Security Settings (https://www.google.com/settings/security/lesssecureapps) and enable "Access for less secure apps", this allows you to use the google smtp for clients other than the official ones.
Update
Google has been so kind as to list all the potential problems and fixes for us. Although I recommend trying the less secure apps setting. Be sure you are applying these to the correct account.
- If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.
- Sign in to your account from the web version of Gmail at https://mail.google.com. Once you’re signed in, try signing in
to the mail app again.- Visit http://www.google.com/accounts/DisplayUnlockCaptcha and sign in with your Gmail username and password. If asked, enter the
letters in the distorted picture.- Your app might not support the latest security standards. Try changing a few settings to allow less secure apps access to your account.
- Make sure your mail app isn't set to check for new email too often. If your mail app checks for new messages more than once every 10
minutes, the app’s access to your account could be blocked.
You could put "element 2" in a smaller column (ie: col-2
) and then use push
on larger screens only:
<div class="row">
<div class="col-lg-6 col-xs-6">elements 1</div>
<div class="col-lg-6 col-xs-6">
<div class="row">
<div class="col-lg-2 col-lg-push-10 col-md-2 col-md-push-0 col-sm-2 col-sm-push-0 col-xs-2 col-xs-push-0">
<div class="pull-right">elements 2</div>
</div>
</div>
</div>
</div>
Demo: http://bootply.com/88095
Another option is to override the float of .pull-right
using a @media query..
@media (max-width: 1200px) {
.row .col-lg-6 > .pull-right {
float: none !important;
}
}
Lastly, another option is to create your own .pull-right-lg
CSS class..
@media (min-width: 1200px) {
.pull-right-lg {
float: right;
}
}
UPDATE
Bootstrap 4 includes responsive floats, so in this case you'd just use float-lg-right
.
No extra CSS is needed.
you have to initialize it "by hand" :
char* c = new char[length];
for(int i = 0;i<length;i++)
c[i]='\0';
Just for completeness and those unaware XSL 1 has choose for multiple conditions.
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:when test="another-expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
If you dig into NSInteger's implementation:
#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
Simply, the NSInteger typedef does a step for you: if the architecture is 32-bit, it uses int
, if it is 64-bit, it uses long
. Using NSInteger, you don't need to worry about the architecture that the program is running on.
Actually you can also make the Junit test a runnable Jar and call the runnable jar as java -jar
Java 8
public static void main(String[] args) throws IOException {
Path start = Paths.get("C:\\data\\");
try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
List<String> collect = stream
.map(String::valueOf)
.sorted()
.collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
sorry I saw the question late, Here is an easy programmatically solution that works well on me,
Create those global variables:
float firstWidth;
float firstHeight;
after on load, fill those variables;
firstWidth = this.Size.Width;
firstHeight = this.Size.Height;
then select your form and put these code to your form's SizeChange event;
private void AnaMenu_SizeChanged(object sender, EventArgs e)
{
float size1 = this.Size.Width / firstWidth;
float size2 = this.Size.Height / firstHeight;
SizeF scale = new SizeF(size1, size2);
firstWidth = this.Size.Width;
firstHeight = this.Size.Height;
foreach (Control control in this.Controls)
{
control.Font = new Font(control.Font.FontFamily, control.Font.Size* ((size1+ size2)/2));
control.Scale(scale);
}
}
I hope this helps, it works perfect on my projects.
Keeping it simple is the key.
Try Below.
var values = new int[5,7,3];
values = values.OrderBy(p => p).ToList();
2008 Answer The "Official" Java API for this is now JAXB - Java API for XML Binding. See Tutorial by Oracle. The reference implementation lives at http://jaxb.java.net/
2018 Update Note that the Java EE and CORBA Modules are deprecated in SE in JDK9 and to be removed from SE in JDK11. Therefore, to use JAXB it will either need to be in your existing enterprise class environment bundled by your e.g. app server, or you will need to bring it in manually.
After reading the answer from Gilles, I decided to see if the $BASH_COMMAND
var was also available (and the desired value) in an EXIT
trap - and it is!
So, the following bash script works as expected:
#!/bin/bash
exit_trap () {
local lc="$BASH_COMMAND" rc=$?
echo "Command [$lc] exited with code [$rc]"
}
trap exit_trap EXIT
set -e
echo "foo"
false 12345
echo "bar"
The output is
foo
Command [false 12345] exited with code [1]
bar
is never printed because set -e
causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345
passed to false
is just there to show that the arguments to the failed command are captured as well (the false
command ignores any arguments passed to it)
200,300, 400, 500 are all very generic. If you want generic, 400 is OK.
422 is used by an increasing number of APIs, and is even used by Rails out of the box.
No matter which status code you pick for your API, someone will disagree. But I prefer 422 because I think of '400 + text status' as too generic. Also, you aren't taking advantage of a JSON-ready parser; in contrast, a 422 with a JSON response is very explicit, and a great deal of error information can be conveyed.
Speaking of JSON response, I tend to standardize on the Rails error response for this case, which is:
{
"errors" :
{
"arg1" : ["error msg 1", "error msg 2", ...]
"arg2" : ["error msg 1", "error msg 2", ...]
}
}
This format is perfect for form validation, which I consider the most complex case to support in terms of 'error reporting richness'. If your error structure is this, it will likely handle all your error reporting needs.
$('#signup').on("submit", function(event) {
$form = $(this); //wrap this in jQuery
alert('the action is: ' + $form.attr('action'));
});
You can't create a 'const' array because arrays are objects and can only be created at runtime and const entities are resolved at compile time.
What you can do instead is to declare your array as "readonly". This has the same effect as const except the value can be set at runtime. It can only be set once and it is thereafter a readonly (i.e. const) value.
I still had a dark grey line after attempting the other answers. I had to add the following two lines to make everything "invisible" in terms of row lines between cells.
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.separatorColor = [UIColor clearColor];
I can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.
Anyway, you shouldn't hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:
data: JSON.stringify({ name : "AA" }),
Now on the server also make sure that you have the proper view model expecting to receive this input:
public class UserViewModel
{
public string Name { get; set; }
}
and the corresponding action:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
}
Now there's one more thing. You have specified dataType: 'json'
. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
return Json(new { Foo = "bar" });
}
This being said, in most cases, usually you don't need to set the dataType
property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult
(such as a ViewResult
or a JsonResult
), the framework will automatically set the correct Content-Type
response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.
I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).
One more thing that I just noticed:
async: false,
Please, avoid setting this attribute to false. If you set this attribute to false
you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.
If you have a file of your font, then you will need to add more formats of that font for other browsers.
For this purpose I use font generator like Fontsquirrel it provides all the font formats & its @font-face CSS, you will only need to just drag & drop it into your CSS file.
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.
Passwords in the database should be stored encrypted. One way encryption (hashing) is recommended, such as SHA2, SHA2, WHIRLPOOL, bcrypt DELETED: MD5 or SHA1. (those are older, vulnerable
In addition to that you can use additional per-user generated random string - 'salt':
$salt = MD5($this->createSalt());
$Password = SHA2($postData['Password'] . $salt);
createSalt()
in this case is a function that generates a string from random characters.
EDIT: or if you want more security, you can even add 2 salts: $salt1 . $pass . $salt2
Another security measure you can take is user inactivation: after 5 (or any other number) incorrect login attempts user is blocked for x minutes (15 mins lets say). It should minimize success of brute force attacks.
Spring started off as a fairly simple dependency injection system. Now it is huge and has everything in it (except for the proverbial kitchen sink).
But fear not, it is quite modular so you can use just the pieces you want.
To see where it all began try:
It might be old but it is an excellent book.
For another good book this time exclusively devoted to Spring see:
It also references older versions of Spring but is definitely worth looking at.
One can avoid the AttributeError
brought about by set_axis_labels()
method by using the matplotlib.pyplot.xlabel
and matplotlib.pyplot.ylabel
.
matplotlib.pyplot.xlabel
sets the x-axis label while the matplotlib.pyplot.ylabel
sets the y-axis label of the current axis.
Solution code:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)
Output figure:
You can also use fpdf class available at: http://www.fpdf.org. It gives options for both outputting to a file and displaying on browser.
In this case, the name of the selector is wrong. The colon here is part of the method signature; it means that the method takes one argument. I believe that you want
SEL sel = @selector(lowercaseString);
You can make you request headers by yourself using:
// open a socket connection on port 80
$fp = fsockopen($host, 80);
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
// close the socket connection:
fclose($fp);
Like writen on how make request
It is best practice to always supply the permission when registering the receiver, otherwise you will receive for any application that sends a matching intent. This can allow malicious apps to broadcast to your receiver.
Had the same problem here but a different solution worked.
First, I tried the following, none of which worked:
Load symbols as suggested by seanlitow
Remove/Add reference to PresentationFramework and PresentationCore
The solution was to undo the last few changes I had made to my code. I had just added a couple radio buttons and event handlers for checked and unchecked events. After removing my recent changes everything compiled. I then added my exact changes back and everything compiled properly. I don't understand why this worked - only thing I can think of is a problem with my VS Solution. Anyway, if none of the other suggestions work, you might try reverting back your most recent changes. NOTE: if you close & re-open Visual Studio your undo history is lost.. so you might try this before you close VS.
This idea can apply?. If you use CountdownLatches or Semaphores works perfect but if u are looking for the easiest answer for an interview i think this can apply.
You can have a pair of extension methods to make this task easier:
public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
return lst.ToDelimitedString(p => p, separator);
}
public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector,
string separator = ", ")
{
return string.Join(separator, lst.Select(selector));
}
So now just:
new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.
Something like this:
typedef struct vec
{
unsigned char* _mem;
unsigned long _elems;
unsigned long _elemsize;
unsigned long _capelems;
unsigned long _reserve;
};
vec* vec_new(unsigned long elemsize)
{
vec* pvec = (vec*)malloc(sizeof(vec));
pvec->_reserve = 10;
pvec->_capelems = pvec->_reserve;
pvec->_elemsize = elemsize;
pvec->_elems = 0;
pvec->_mem = (unsigned char*)malloc(pvec->_capelems * pvec->_elemsize);
return pvec;
}
void vec_delete(vec* pvec)
{
free(pvec->_mem);
free(pvec);
}
void vec_grow(vec* pvec)
{
unsigned char* mem = (unsigned char*)malloc((pvec->_capelems + pvec->_reserve) * pvec->_elemsize);
memcpy(mem, pvec->_mem, pvec->_elems * pvec->_elemsize);
free(pvec->_mem);
pvec->_mem = mem;
pvec->_capelems += pvec->_reserve;
}
void vec_push_back(vec* pvec, void* data, unsigned long elemsize)
{
assert(elemsize == pvec->_elemsize);
if (pvec->_elems == pvec->_capelems) {
vec_grow(pvec);
}
memcpy(pvec->_mem + (pvec->_elems * pvec->_elemsize), (unsigned char*)data, pvec->_elemsize);
pvec->_elems++;
}
unsigned long vec_length(vec* pvec)
{
return pvec->_elems;
}
void* vec_get(vec* pvec, unsigned long index)
{
assert(index < pvec->_elems);
return (void*)(pvec->_mem + (index * pvec->_elemsize));
}
void vec_copy_item(vec* pvec, void* dest, unsigned long index)
{
memcpy(dest, vec_get(pvec, index), pvec->_elemsize);
}
void playwithvec()
{
vec* pvec = vec_new(sizeof(int));
for (int val = 0; val < 1000; val += 10) {
vec_push_back(pvec, &val, sizeof(val));
}
for (unsigned long index = (int)vec_length(pvec) - 1; (int)index >= 0; index--) {
int val;
vec_copy_item(pvec, &val, index);
printf("vec(%d) = %d\n", index, val);
}
vec_delete(pvec);
}
Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.
If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.
SELECT TRIM(ColumnName) from TableName;
For other SQL SERVER Database you can use the below query.
SELECT LTRIM(RTRIM(ColumnName)) from TableName
LTRIM - Removes spaces from the left
example: select LTRIM(' test ') as trim
= 'test '
RTRIM - Removes spaces from the right
example: select RTRIM(' test ') as trim
= ' test'
In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.
PHP has no explicit byte
type, but its string
is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …")
. The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.
Now you can hover the key input and select "file", which will give you a file selector in the value column:
I have the same problem now , I have foreign key and i need put it as nullable, to solve this problem you should put
modelBuilder.Entity<Country>()
.HasMany(c => c.Users)
.WithOptional(c => c.Country)
.HasForeignKey(c => c.CountryId)
.WillCascadeOnDelete(false);
in DBContext class I am sorry for answer you very late :)
Quite simply, that string is not valid JSON. As the error says, JSON documents need to use double quotes.
You need to fix the source of the data.
A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.
You can modify cookies using document.cookie
.
You can easily find many examples how to modify cookies.
The changed it from change
to selectionChange
.
<mat-select (change)="doSomething($event)">
is now
<mat-select (selectionChange)="doSomething($event)">
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
I think the $() syntax is easier to read...
variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')
But the real issue is probably that $12
should not be qouted with ""
Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef
is and what is expected in variable.
Depending on some details you might need to do something like this:
r=$(pwd)
case "$TARG" in
/*) p=$r;;
*) p="";;
esac
cd "$SRC" && cp -r . "$p/$TARG"
cd "$r"
... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.
The extra fussing is to handle relative or absolute targets.
(This doesn't rely on subtle semantics of the cp
command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp
and I don't know if they'll continue to be so in the future).